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]
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
– Elton Nunes
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?– Lucas
I could use self.value within another method?
– Lucas
@Hartnäcking just to get you an answer, you want the
meaning
is an attribute after initializing an object with the__init__
right ?– JeanExtreme002
yes. For
meaning
will need some information present at object startup– Lucas
just don’t use self, however you have to be attentive to the initialization of the same
– Elton Nunes