Skip to content Skip to sidebar Skip to footer

Property In Python With @property.getter

I have an intresting behaviour for the following code: class MyClass: def __init__(self): self.abc = 10 @property def age(self): return self.abc @

Solution 1:

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:

classMyClass(object):
    # body as is

obj = MyClass()
print(obj.age)   # 20
obj.age = 12print(obj.age)   # 22
obj.age = 11print(obj.age)   # 21

Post a Comment for "Property In Python With @property.getter"