Attributes Vs Properties
class Person():
def __init__(self):
self._name = "test"
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = valueGiven the above class, attributes are stored in a dictionary __dict__.
a = Person()
# both gives the same result.
a._name # "test"
a.name # "test"
# However, "name" as an attribute is not present in __dict__
print(a.__dict__)
{'_name': 'test'}We can set attribute by changing the a.__dict__ elements.
a.__dict__['_name'] = "some-name"
a._name # "some-name"
a.name # "some-name"Changing attributes like below changes the corresponding value inside __dict__.
a._name = "good name"
a._name # "good name"When an attribute is accessed on an object, it looks in the __dict__ first and then moves to next finding if not found in __dict__.
Python distinguishes between properties and attributes by their implementation. Properties are not stored in __dict__.