Question

Take this simple example class:

class vec:
   def __init__(self,v=(0,0,0,0)):
       self.v = list(v)

   @property
   def x(self):
       return self.v[0]

   @x.setter
   def set_x(self, val):
       self.v[0] = val

...and this usage:

>> a = vec([1,2,3,4])
>> a.v
[1,2,3,4]
>> a.x
1
>> a.x = 55
>> a.x
55
>> a.v
[1,2,3,4]

Why do the member array (specifically, self.v[0]) and the reported property value disagree? If it's not in self.v, where is the altered property value coming from?

Was it helpful?

Solution

You should use new-style class. And the name of the setter should be x, not set_x.

class vec(object): # <-----
   def __init__(self,v=(0,0,0,0)):
       self.v = list(v)

   @property
   def x(self):
       return self.v[0]

   @x.setter
   def x(self, val): # <--------
       self.v[0] = val

According to property documentation:

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

If you don't use new-style class, a.x = ... creates a new attribute x instead of calling the setter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top