I have an intresting behaviour for the following code:
class MyClass:def __init__(self):self.abc = 10@propertydef age(self):return self.abc@age.getterdef age(self):return self.abc + 10@age.setterdef age(self, value):self.abc = valueobj = MyClass()
print(obj.age)
obj.age = 12
print(obj.age)
obj.age = 11
print(obj.age)
And I have the following result:
20
12
11
Can somebody explain this behaviour ?
On old style classes (which yours is if you're executing on Python 2
) the assignment obj.age = 11
will 'override' the descriptor. See New Class vs Classic Class:
New Style classes can use descriptors (including __slots__
), and Old Style classes cannot.
You could either actually execute this on Python 3
and get it executing correctly, or, if you need a solution that behaves similarly in Python 2 and 3, inherit from object
and make it into a New Style Class:
class MyClass(object):# body as isobj = MyClass()
print(obj.age) # 20
obj.age = 12
print(obj.age) # 22
obj.age = 11
print(obj.age) # 21