I have the following Python code snippet.
class LoggedAgeAccess:
def __get__(self, obj, objtype=None):
value = obj._age
return value
def __set__(self, obj, value):
obj._age = value
class Person:
age = LoggedAgeAccess() # Descriptor instance
def __init__(self, name, age):
self.name = name # Regular instance attribute
self.age = age # Calls __set__()
def birthday(self):
self.age += 1 # Calls both __get__() and __set__()
x = Person("ABC", 27)
In the constructor, the second assignment statement self.age = age
triggers the __set__()
method of the LoggedAgeAccess descriptor.
This is really confusing.
When the Person object is created, I am passing name and age values. Inside the constructor, I refer the passed value and create a instance specific variable self.age
whose value is assigned with the passed value (27). How this assignment statement refers the class level age variable and triggers a call to __set__()
?
1