Python getter / setter property confusion

I am 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.aN @N.setter def N(self,v): print("B setter") self.aN = v def __init__(self): self.a = A() if __name__ == '__main__': b=B() bN = 2 print(bN, baN) bN = 3 print(bN, baN) 

B should be something like a wrapper for A. It uses getters and setters to map properties on itself (of course, this can also be done through inheritance). The problem is that it just doesn't work as expected in python2.6 while it works 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 something wrong or where exactly is the problem?

+8
python properties getter-setter
source share
1 answer

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

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

Returns the property attribute for the new style classes (classes that come from object ).

So if you exit object

 class A(object): ... class B(object): ... 

Your code will work as expected.

+18
source share

All Articles