override a property on a subclass in python

To override a property on a subclass in python, you need to define the property with the same name on the subclass and provide a new implementation. This can be done using the @property decorator on the subclass method.

Here is an example:

main.py
class Parent:
    @property
    def my_property(self):
        return "Parent property"

class Child(Parent):
    @property
    def my_property(self):
        return "Child property"
183 chars
10 lines

In this example, the Parent class defines a my_property property using the @property decorator. The Child class then overrides this property and provides a new implementation that returns a different value.

When you create an instance of the Child class and access the my_property property, the overridden implementation will be called:

main.py
child = Child()
print(child.my_property) # Output: "Child property"
68 chars
3 lines

Note that if you want to access the original implementation of the my_property property defined in the Parent class, you can do so using the super() function. For example:

main.py
class Child(Parent):
    @property
    def my_property(self):
        parent_property = super().my_property()
        return f"Child property \n Parent property: {parent_property}"
181 chars
6 lines

In this example, the Child class again overrides the my_property property, but also calls the original implementation in the Parent class using the super() function. The parent_property variable then contains the result of calling the original implementation, which can be used in the new implementation of the Child class.

gistlibby LogSnag