The following example shows how to add a setter in a derived class to the getter property x
of the base class Foo
.
class Foo:
def __init__(self):
self._x = "I'm Foo.x"
@property
def x(self):
return self._x
class Bar(Foo):
@Foo.x.setter
def x(self, value):
self._x = value
When executed, it looks like this:
>>> b = Bar()
>>> b.x
"I'm Foo.x"
>>> b.x = "I'm Bar.x"
>>> b.x
"I'm Bar.x"
Furthermore, if you want to add a deleter, write as follows.
class Foo:
def __init__(self):
self._x = "I'm Foo.x"
@property
def x(self):
return self._x
class Bar(Foo):
@Foo.x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
self._x = "Nothing"
When executed, it will be as follows.
>>> b = Bar()
>>> b.x
"I'm Foo.x"
>>> b.x = "I'm Bar.x"
>>> b.x
"I'm Bar.x"
>>> del b.x
'Nothing'
Note that the last decorator is @ x.deleter
, not@Foo.x.deleter
.
If you do @ Foo.x.deleter
, a property without a setter will be generated.
The deleter
method of the property
object returns a new property
object with the argument function added to the deleter. Foo.x
is a property object that has only getters
A definition that starts with the @ Foo.x.setter
decorator of Bar
, and property
with getters and setters in Bar.x
.
Since the object has been created and assigned, @ x.deleter
will add the deleter in addition to the getter and setter.
reference
Recommended Posts