-As the title implies, I already know how the decorator works property
, it simply creates a class attribute and constantly updates it with the methods we define. However, I don't quite understand why it generates a class attribute and not an instance attribute, I consider this much worse... Obviously there is a reason for that, so the question would be: "what is the reason why property creates class attributes and not instance attributes"
Plot ...
class persona:
def __init__(self, nombre, apellido):
self.nombre = nombre
self.apellido = apellido
@property
def nombre_completo(self):
return self.nombre.capitalize() + ' ' + self.apellido.capitalize()
@nombre_completo.setter
def nombre_completo(self, nuevo_nombre):
nombre,apellido = nuevo_nombre.split(' ')
self.nombre = nombre
self.apellido = apellido
@nombre_completo.deleter
def nombre_completo(self):
del persona.nombre_completo
persona_nueva = persona('Juan', 'Peres')
print(persona_nueva.nombre_completo)
persona.nombre_completo = 'Nelson Martinez'
print(persona_nueva.nombre_completo)
print(persona.nombre_completo)
print(persona.__dict__['nombre_completo'])
To answer this we must refer to the engine behind
property
: The Descriptor Protocol.Basically, this is that every object that is an attribute of another object and that contemplates the methods
__get__
and (optionally)__set__
and (optionally)__del__
, is treated in a special way by the interpreter when said object is invoked for its reading. , write or erase, respectively.However, for this to happen, the object must be declared as a class variable of the class through which the object is to be referenced.
As I already mentioned, the type
property
implements the Descriptor Protocol. This is how we can magically define behaviors to be executed for the establishment, access and elimination of the attributes decorated with this type.So yes, basically the answer to your question is given by the inherent rules of this protocol. In fact, in its own documentation it says this exhaustively:
I really don't understand why you consider it worse than it being an instance attribute, or what benefit you see if it were. It would be interesting to know what advantages you think there might be. However, I'm sure that by reading Raymond Hettinger's (excellent) guide that I referenced above, you will be able to understand in depth that the use cases for which descriptors are used are perfectly covered in the way that they have already been. conceived.