Inheritance and Polymorphism
Inheritance:
1. Defining Subclasses:
- Creating a subclass by inheriting from a superclass (base class).
- Using the class Subclass(Superclass) syntax.
2. Accessing Superclass Methods and Attributes:
- Subclasses inherit methods and attributes from the superclass.
- Accessing inherited methods and attributes using dot notation.
3. Adding Additional Attributes and Methods:
- Extending the subclass with its own attributes and methods.
- Enhancing the functionality of the subclass.
4. Method Overriding:
- Redefining methods in the subclass with the same name as the superclass.
- Changing or enhancing the behavior of inherited methods.
5. Using super():
- Calling overridden methods from the superclass using the super() function.
- Ensuring proper execution of both subclass and superclass methods.
6. Multiple Inheritance:
- Inheriting from multiple superclasses.
- Managing method resolution order (MRO) using the C3 linearization algorithm.
Polymorphism:
1. Polymorphism Basics:
- Polymorphism allows objects of different classes to be treated as objects of a common superclass.
- Code that works with a superclass can also work with its subclasses.
2. Method Overriding and Polymorphism:
- Using method overriding to achieve polymorphism.
- Different subclasses can provide different implementations for the same method.
3. Duck Typing:
- Polymorphism based on object behavior rather than inheritance.
- If an object behaves like a certain type, it's treated as that type.
4. Using Polymorphism:
- Treating objects of different subclasses as instances of the superclass.
- Calling common methods on different objects.
Example:
Let's illustrate inheritance and polymorphism with an example:
class Animal: def speak(self): pass
class Dog(Animal): def speak(self): return "Woof!"
class Cat(Animal): def speak(self): return "Meow!"
# Using polymorphism animals = [Dog(), Cat()]
for animal in animals: print(animal.speak())
|