override a setter on a subclass in python

To override a setter method on a subclass in Python, you can simply define the same setter method on the subclass and provide the new implementation. Here's an example:

main.py
class Parent:
    def __init__(self, val):
        self._val = val

    @property
    def val(self):
        return self._val

    @val.setter
    def val(self, new_val):
        self._val = new_val


class Child(Parent):
    @Parent.val.setter
    def val(self, new_val):
        self._val = new_val + 1
305 chars
18 lines

In this example, Child inherits from Parent, but overrides the val setter. We do this by defining Child.val as a setter and using the @Parent.val.setter decorator to indicate that we are overriding the parent's val setter.

When we call Child().val = 5, for example, it will set _val to 6 because of the overridden val setter.

Keep in mind that the overridden setter will only be used when setting the value of val on instances of Child or any of its subclasses, but not on instances of Parent.

gistlibby LogSnag