-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
5.3.1 Extending classes and method overriding
In Python, extending classes and method overriding are key concepts in Object-Oriented Programming (OOP). They allow you to build more specialized versions of existing classes by inheriting their attributes and methods and modifying them to suit your needs.
Extending Classes (Inheritance)
Extending a class in Python refers to creating a child class that inherits the behavior (attributes and methods) of an existing parent class. This allows the child class to reuse code from the parent class and add additional functionality or change the behavior.
Example of Extending a Class:
# Parent Class class Animal: def __init__(self, name): self.name = name def speak(self): print(f"{self.name} makes a sound.") # Child Class extending Animal class Dog(Animal): def __init__(self, name, breed): super().__init__(name) # Calling the parent class constructor self.breed = breed def speak(self): # Overriding the speak method print(f"{self.name}, a {self.breed}, barks.") # Create an instance of Dog dog = Dog("Buddy", "Golden Retriever") dog.speak() # Output: Buddy, a Golden Retriever, barks.
- Inheriting Properties: The Dog class inherits the __init__ and speak() methods from the Animal class.
- Calling Parent Constructor: The super() function is used to call the parent class's __init__ method, allowing the child class to initialize the inherited properties.
Method Overriding
Method overriding occurs when a child class provides its own implementation of a method that is already defined in the parent class. By overriding the method, the child class can change or extend the behavior of the parent class's method.
How Method Overriding Works:
- The child class defines a method with the same name as the parent class's method.
- The method in the child class will override (replace) the method in the parent class when called on an instance of the child class.
Example of Method Overriding:
# Parent Class class Animal: def speak(self): print("The animal makes a sound.") # Child Class overriding speak method class Cat(Animal): def speak(self): # Overriding the speak method print("The cat meows.") # Creating instances animal = Animal() cat = Cat() animal.speak() # Output: The animal makes a sound. cat.speak() # Output: The cat meows.
- In this case, the speak() method in the Animal class is overridden by the speak() method in the Cat class. When the speak() method is called on an instance of Cat, the overridden version is executed.
Why Use Method Overriding?
Method overriding allows you to:
- Customize Behavior: Modify or extend the behavior of a method from the parent class to meet the specific needs of the child class.
- Polymorphism: Achieve polymorphism, where the same method name behaves differently based on the object type (i.e., method in Cat behaves differently than in Animal).
- Maintainability: Overriding helps to keep code clean, organized, and maintainable by allowing you to adjust inherited functionality without modifying the parent class.
Example of Inheritance with Method Overriding:
# Parent Class class Vehicle: def __init__(self, make, model): self.make = make self.model = model def start(self): print("Starting the vehicle.") # Child Class overriding start method class Car(Vehicle): def start(self): # Overriding the start method print(f"Starting the {self.make} {self.model} car.") # Child Class overriding start method class Motorcycle(Vehicle): def start(self): # Overriding the start method print(f"Starting the {self.make} {self.model} motorcycle.") # Create instances of Car and Motorcycle car = Car("Toyota", "Corolla") motorcycle = Motorcycle("Harley Davidson", "Sportster") car.start() # Output: Starting the Toyota Corolla car. motorcycle.start() # Output: Starting the Harley Davidson Sportster motorcycle.
In this example:
- The Vehicle class has a method start(), but both the Car and Motorcycle classes override it to provide more specific behavior when the method is called.
Important Points about Extending Classes and Method Overriding:
- Access to Parent Class Methods: The child class can still access methods from the parent class using super(). This is useful when you want to extend or build upon a parent method rather than completely replacing it.
- Method Resolution Order (MRO): Python determines the order in which methods are inherited when multiple inheritance is involved. The MRO specifies the order in which classes are checked for a method definition. It ensures that the correct method is invoked based on the class hierarchy.
-
Overriding vs. Overloading:
- Overriding: Occurs when a method in a child class has the same name and parameters as in the parent class, but its behavior is different.
- Overloading: Python does not directly support method overloading (having multiple methods with the same name but different parameters). However, it can be simulated by using default arguments or variable-length arguments (*args, **kwargs).
Conclusion:
- Extending Classes via inheritance allows you to build upon existing functionality in Python. It provides an efficient way to reuse and extend code.
- Method Overriding gives you the ability to modify or replace methods in the parent class, enabling you to customize or specialize functionality for child classes.
Together, inheritance and method overriding facilitate more modular, maintainable, and flexible code in Python by encouraging code reuse and allowing behavior customization in child classes.
Commenting is not enabled on this course.