简体   繁体   中英

Use parent property setter when overriding in child class

I have a situation where I am overriding just the setter on a property:

class Parent:
    @property
    def x(self):
        return self.__dict__['x']
    @x.setter
    def x(self, val):
        self.__dict__['x'] = f'P{val}'

class Child(Parent):
    @Parent.x.setter
    def x(self, val):
         super().x = val
         print('all set')

Here, the print statement represents the processing I want to do after invoking the parent's setter. You can just ignore it. super().x = y is my native attempt at invoking said setter. It fails with

Attribute error: 'super' object has no attribute 'x'

What is the correct way to use the property setter from the parent class in the child?

I'd prefer to avoid the following, even though it works just fine, since it involves explicitly calling dunder methods:

Parent.x.__set__(self, val)

As a bonus, is there any way to use super() in the body of the child's setter?

You can use the property's fset function:

class Child(Parent):
    @Parent.x.setter
    def x(self, val):
        Parent.x.fset(self, val)
        print('all set')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM