-3
I’m trying to implement a simple Python code to practice using decorators in conjunction with advisory methods (Getters and Setters), but I’m getting an error.
The code is as follows::
class Pessoa():
def __init__(self, anos):
self._idade = 0
self.idade = anos
@idade.setter
def idade(self, anos):
self._idade = anos
alguem = Pessoa(18)
And the error that is occurring is as follows:
NameError: name 'idade' is not defined
I do not understand, because 'age' does exist!
I searched on the internet for examples of use of decorators in conjunction with advisory methods and found some codes, but could not figure out where I am missing.
There is a way to implement only the Setter method with decorators?
I would change in the
__init__
forself.idade = anos
to use the property instead of setting the attribute value directly.– Woss
I understood, but there were two other questions: 1° - Is there a way to implement only the Setter method using decorators? 2° - When you write
self._idade = anos
, this does not cause the value of years to be attributed directly toself._idade
, thus disabling the created Setter method?– Edy
@Edy I think the recommended is that you try to delve into the question of encapsulation... these Protect and private in Python do not follow the pattern of other languages. In the case of the last questions... 1- if the attribute is Protect or private will not be accessed without the @Property, even if you use @Setter. 2- The self_age receives the value of years without any problem, the issue is that the variable information will not be accessible if the data is not treated with the encapsulation methods.
– Victor Dantas
@Victordantas Thanks for the advice! I will seek to deepen more in the themes related to POO in Python, and mainly on encapsulation. Another thing: I forgot to explain that when I wrote
self.idade = anos
instead of creating another name attribute similar to the first one, I was actually using the property used in Setter and passing the value.– Edy