Python object @property

I am trying to create a point class that defines a coordinate property. However, it does not behave as I expected, and I cannot understand why.

class Point: def __init__(self, coord=None): self.x = coord[0] self.y = coord[1] @property def coordinate(self): return (self.x, self.y) @coordinate.setter def coordinate(self, value): self.x = value[0] self.y = value[1] p = Point((0,0)) p.coordinate = (1,2) >>> px 0 >>> py 0 >>> p.coordinate (1, 2) 

It seems that px and py are not installing for some reason, although the installer "should" set these values. Does anyone know why this is?

+6
python
source share
2 answers

The property method (and by extension, the @property decorator) requires a new style class , that is, a class that subclasses object .

For example,

 class Point: 

it should be

 class Point(object): 

In addition, the setter attribute (along with others) was added in Python 2.6. A.

+9
source share

It will work if you select Point from object:

 class Point(object): # ... 
+4
source share

All Articles