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.py183 chars10 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.py68 chars3 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.py181 chars6 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