Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
Mad Physicist Avatar asked Oct 17 '22 14:10

Mad Physicist


1 Answers

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')
like image 81
Martin Stone Avatar answered Oct 21 '22 04:10

Martin Stone