Property getter/setter have no effect in Python 2
Asked Answered
D

1

11

I'm a bit confused about properties in python. Consider the following code

class A:
    @property
    def N(self):
        print("A getter")
        return self._N
    @N.setter
    def N(self,v):
        print("A setter")
        self._N = v

    def __init__(self):
        self._N = 1

class B:
    @property
    def N(self):
        print("B getter")
        return self.a.N
    @N.setter
    def N(self,v):
        print("B setter")
        self.a.N = v

    def __init__(self):
        self.a = A()

if __name__ == '__main__':
    b=B()
    b.N = 2
    print(b.N, b.a.N)
    b.N = 3
    print(b.N, b.a.N)

B should be something like a wrapper for A. It uses getters and setters to map A's properties on itself (of course one could also do it via inheritance). The problem is, that it simply doesn't work as expected in python2.6 while it does in python3:

> python2 test.py
A getter
(2, 1)
A getter
(3, 1)

> python3 test.py
B setter
A setter
B getter
A getter
A getter
2 2
B setter
A setter
B getter
A getter
A getter
3 3

Am I doing anything wrong or where exactly is the problem?

Droll answered 6/2, 2012 at 16:58 Comment(0)
P
28

A and B must be new-style classes in Python 2.x.

property([fget[, fset[, fdel[, doc]]]])

Return a property attribute for new-style classes (classes that derive from object).

So if you'll derive from object

class A(object):
   ...

class B(object):
    ...

Your code will work as expected.

Proximity answered 6/2, 2012 at 17:4 Comment(2)
ok you're right, that solves it but i don't anyway understand what goes wrong here.Droll
@Droll Old-style classes can't have descriptors. @property is descriptor. More info at Python Data model referenceProximity

© 2022 - 2024 — McMap. All rights reserved.