[PYTHON] Precautions when adding setter and deleter in derived class to getter property of base class

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

Precautions when adding setter and deleter in derived class to getter property of base class
Precautions when passing def to sorted and groupby functions in Python? ??
Precautions when adding items using DateField to an existing model later in Django
Differences in behavior between append () and "+ =" operators when adding data to a list in Python
setter and getter
Tips and precautions when porting MATLAB programs to Python
Sample of getting module name and class name in Python