Denis Kotov
Denis Kotov

Reputation: 882

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

    @age.getter
    def age(self):
        return self.abc + 10

    @age.setter
    def age(self, value):
        self.abc = value

obj = 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 ?

Upvotes: 0

Views: 974

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

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 is

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

Upvotes: 1

Related Questions