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.py305 chars18 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