How do I build attributes based on values defined in the __init__ method in my class?

Asked

Viewed 74 times

2

I wrote the following class:

class Words():
    def __init__(self, value, g_class, first_meaning = True):
        self.value = value
        self.g_class = g_class
        self.first_meaning = first_meaning
    #attribute meaning
    meaning = ''
    #is the word in my local dictionary?
    if self.value in brecht_dict.keys():
            self.meaning = brecht_dict[self.value]

The arguments value, g_class and first_meaing are, respectively, the string that corresponds to the word, its grammatical class and whether the user wants all dictionary entries referring to that word or only the first. That part of the code normally runs.

However, I would like to create an attribute called meaning which returns the meaning of the word. What I tried to do was to create meaning as an empty string first and then check if I have it in an internal dictionary. It occurs when I do this the program returns the following error:

name 'self' is not defined

It’s clear to me that self exists only within the method, but how do I call the value of value out of method?

  • look at the identation, if this out of method, it is in the overall scope, arrange the identation inside the method init, or create another method

  • I know. I want to create an attribute outside the same method. meaning would not be an attribute in a particular method, only of the class. This is possible, right?

  • I could use self.value within another method?

  • @Hartnäcking just to get you an answer, you want the meaning is an attribute after initializing an object with the __init__ right ?

  • yes. For meaning will need some information present at object startup

  • just don’t use self, however you have to be attentive to the initialization of the same

Show 1 more comment

1 answer

4


First of all, this error there occurs because during the definition of your class, there is still no object, so there is no self. And for this reason, it is not possible for you to check whether you have the desired value in the dictionary outside of a method.

Also, the verification code will already be executed when defining the class, as you can see in this simple example I did:

class App():

    with open("settings.txt") as settings:

        if settings.read() == "pt-br":
            msg = "Olá! Como você está ?"
        else:
            msg = "Hello! How are you ?"

    def hello(self):
        print(self.msg)

In this example the code outside the method is executed even before I create an object, where a settings file is read and the attribute msg is defined according to the language inside the file.


What you can do in this case, is perform the verification within the method __init__, thus:

class Words():

    def __init__(self, value, g_class, first_meaning = True):

        self.value = value
        self.g_class = g_class
        self.first_meaning = first_meaning

        if value in brecht_dict.keys():
            self.meaning = brecht_dict[value]

It is also possible to define you through the __init__ the meaning as a static attribute, passing the class name instead of the self. But in doing so, it will be "shared" with all other objects, creating another problem for your program. Example:

class Perfil():  
    def __init__(self,nome):
        Perfil.nome = nome

pessoa1 = Perfil('Jean')
print(pessoa1.nome) # Saída: Jean

pessoa2 = Perfil('Larissa')
print(pessoa1.nome) # Saída: Larissa (alterou o nome da primeira pessoa)

Using @Property:

If you want to check the value whenever you want to call the meaning, you can use the @property.

In a very simple way to understand, the @property is a decorator And what he does is he turns a method into a kind of attribute. It is used to restrict the use of an attribute or to execute a code block when calling, modifying, or deleting an attribute. Your code would look like this:

class Words():

    def __init__(self, value, g_class, first_meaning = True):

        self.value = value
        self.g_class = g_class
        self.first_meaning = first_meaning

    @property
    def meaning(self)
        if self.value in brecht_dict.keys():
                return brecht_dict[self.value]
  • Excelente, Jean!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.