what is wrong with this property setter

Mark Summerfield list at qtrac.plus.com
Thu Jun 9 03:49:20 EDT 2016


On Thursday, June 9, 2016 at 8:28:47 AM UTC+1, Nagy László Zsolt wrote:
> class Test:
>     def __init__(self):
>         self._parent = None
> 
>     @property
>     def parent(self):
>         return self._parent
> 
>     @parent.setter
>     def set_parent(self, new_parent):
>         self._parent = new_parent
> 
> 
> p, c = Test(), Test()
> c.parent = p
> 
> >py -3 test.py
> 
> Traceback (most recent call last):
>   File "test.py", line 15, in <module>
>     c.parent = p
> AttributeError: can't set attribute
> 
> BTW this does work, but it is not that elegant:
> 
> class Test:
>     def __init__(self):
>         self._parent = None
> 
>     def get_parent(self):
>         return self._parent
> 
>     def set_parent(self, new_parent):
>         self._parent = new_parent
> 
>     parent = property(get_parent, set_parent)
> 
> 
> p, c = Test(), Test()
> c.parent = p

Change the name of the setter from set_parent to parent, i.e.,

@parent.setter
def parent(self, new_parent):
   ...

That works for me on Python 3.4.


More information about the Python-list mailing list