what is wrong with this property setter
Peter Otten
__peter__ at web.de
Thu Jun 9 04:01:13 EDT 2016
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
Does this interactive session help you solve it yourself?
$ python3 -i test.py
Traceback (most recent call last):
File "test.py", line 15, in <module>
c.parent = p
AttributeError: can't set attribute
>>> [n for n in dir(p) if not n.startswith("_")]
['parent', 'set_parent']
>>> p.set_parent = 42
>>> p.parent
42
Spoiler below if you don't see the light.
> @parent.setter
> def set_parent(self, new_parent):
> self._parent = new_parent
This creates a settable property with the name "set_parent" and leaves the
read-only property "parent" alone. To fix your class change the above to
@parent.setter
def parent(self, new_parent):
self._parent = new_parent
More information about the Python-list
mailing list