101. Overriding Methods
Here are 10 Python code snippets that demonstrate overriding methods by modifying the behavior of inherited methods in a subclass:
1. Basic Method Overriding
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Dog barksExplanation: In the Dog subclass, we override the speak method to provide a custom implementation.
2. Overriding with Arguments
class Vehicle:
def start(self, engine_type):
print(f"{engine_type} engine started")
class Car(Vehicle):
def start(self, engine_type="Petrol"):
print(f"Car with {engine_type} engine started")
car = Car()
car.start() # Output: Car with Petrol engine started
car.start("Diesel") # Output: Car with Diesel engine startedExplanation: In the Car subclass, we override the start method to specify a default argument.
3. Calling the Parent Method with super()
Explanation: In Dog, we call the parent class's speak method before adding our own behavior.
4. Overriding Initialization in Subclass
Explanation: The Student subclass overrides the __init__ method to add a new attribute, while still calling the parent class's __init__.
5. Overriding with Different Return Values
Explanation: The Circle class overrides the area method to compute the area of a circle.
6. Overriding a Class Method
Explanation: We override the class method description in the Car subclass.
7. Overriding a Static Method
Explanation: The static method sound is overridden in the Dog subclass to provide a specific implementation.
8. Overriding Method for Logging
Explanation: FileLogger overrides log to add its own logging mechanism while still calling the parent class's method.
9. Overriding a Method with Exception Handling
Explanation: The Derived class overrides the calculate method to handle exceptions differently.
10. Overriding Methods with Different Parameters
Explanation: The Dog subclass overrides the sound method and adds a parameter for volume control.
These examples demonstrate how to override inherited methods in a subclass to change their behavior, whether it's by modifying their functionality, adding new parameters, or invoking the parent class's method using super().
Last updated