[Tutor] calling setters of superclasses

Steven D'Aprano steve at pearwood.info
Mon Dec 20 11:56:15 CET 2010


Alan Gauld wrote:
> 
> "Gregory, Matthew" <matt.gregory at oregonstate.edu> wrote
>> class PositiveX(object):
>>    def __init__(self):
>>    @property
>>    def x(self):
>>    @x.setter
>>    def x(self, val):
> 
> I don't use properties in Python very often (hardly ever in fact) and 
> I've never used @setter so there may be naming requirements I'm not 
> aware of. But in general I'd avoid having two methods with the same name.

That's generally good advice, since one will over-write the other, but 
in this specific case, the following is completely bad:

> Try renaming the setter to setX() or somesuch and see if you get the 
> same error.

When using the x.setter and x.deleter decorators of a property, you 
*must* use the same name. The example given by help(property) for 
Python2.6 says this:

  |  Decorators make defining new properties or modifying existing ones 
easy:
  |  class C(object):
  |      @property
  |      def x(self): return self._x
  |      @x.setter
  |      def x(self, value): self._x = value
  |      @x.deleter
  |      def x(self): del self._x

and the docs are even more explicit:

http://docs.python.org/library/functions.html#property

If you don't use the same name, chaos reigns:


 >>> class Broken(object):
...     def __init__(self):
...             self._x = 42
...     @property
...     def x(self):
...             return self._x
...     @x.setter
...     def set_x(self, value):
...             self._x = value + 1
...
 >>>
 >>> obj = Broken()
 >>> obj.x
42
 >>> obj.x = 20
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: can't set attribute


-- 
Steven


More information about the Tutor mailing list