what is wrong with this property setter
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Jun 9 03:52:29 EDT 2016
On Thursday 09 June 2016 17:28, Nagy László Zsolt wrote:
> class Test:
Are you using Python 3 or 2? In Python 2, property doesn't work correctly with
classes unless they inherit from object (directly or indirectly).
> 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
If you use the "setter" method, you must use the same name, in this case
"parent", for each part of the property.
If you want to give your getters and setters different names, you have to use
the older property API:
class Test(object):
def get_parent(self): ...
def set_parent(self, value): ...
parent = property(get_parent, set_parent)
The reason why your code doesn't work is because of the way decorator syntax is
defined. You have:
@property
def parent(self): ...
which becomes:
parent = property(parent)
Then you have:
@parent.setter
def set_parent(self, new_parent):
which becomes:
set_parent = parent.setter(set_parent)
which leaves you with TWO property objects, not one:
(1) parent has a getter but no setter;
(2) set_parent has a getter and setter (I think).
--
Steve
More information about the Python-list
mailing list