Method overriding is a fundamental concept in object-oriented programming (OOP) that allows a subclass to provide a specific implementation of a method already defined in its superclass. This powerful feature enables developers to create more specialized behaviors in derived classes while maintaining a common interface.
In Python, method overriding occurs when a subclass defines a method with the same name as a method in its parent class. When the method is called on an instance of the subclass, the overridden method in the subclass is executed instead of the one in the parent class.
To override a method in Python, simply define a method with the same name in the subclass. Here's a simple example:
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
child = Child()
child.greet() # Output: Hello from Child
In this example, the greet()
method in the Child
class overrides the greet()
method in the Parent
class.
Sometimes, you may want to call the parent class's method from within the overridden method. Python's super()
function allows you to do this:
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
child = Child()
child.greet()
# Output:
# Hello from Parent
# Hello from Child
@override
decorator (available in Python 3.12+) to explicitly indicate method overriding.Method overriding is closely related to other OOP concepts in Python:
Method overriding is a powerful tool in Python's OOP toolkit. It allows for the creation of more specialized and flexible class hierarchies, enabling developers to write cleaner, more maintainable code. By mastering this concept, you'll be better equipped to design robust and extensible object-oriented systems in Python.