Show a Python method being overridden, and how the child calls the parent version.
Overriding is simply defining a method with the same name in a subclass. The subclass version is used whenever the method is called on an instance of the subclass.
class Parent:
def greet(self):
return "parent greeting"
class Child(Parent):
def greet(self):
return "child greeting"
def greet_parent(self):
return super().greet()
child = Child()
print(child.greet()) # child greeting
print(child.greet_parent()) # parent greeting
print(isinstance(child, Parent)) # TrueThere is no special syntax for overriding — a method of the same name is enough. The parent implementation is still there and can be reached through super().
The right way to reach the parent is super().greet(), and it is important to use super() rather than naming the parent class directly. super() looks up the next class in the method resolution order of the current instance, which means it stays correct if the class is later combined with a mix-in or re-parented. Writing Parent.greet(self) hard-codes the parent into the child and breaks as soon as the hierarchy changes.
The isinstance check at the end is worth mentioning: an overridden method does not change the object's type relationship. A Child is still a Parent, which means code that expects a Parent can accept a Child without knowing anything about the override.