9 4 2 Multiple Inheritance Explained
Key Concepts
Multiple inheritance in Python involves several key concepts:
- Definition of Multiple Inheritance
- Syntax and Structure
- Method Resolution Order (MRO)
- Diamond Problem
- Practical Applications
1. Definition of Multiple Inheritance
Multiple inheritance is a feature in object-oriented programming where a class can inherit attributes and methods from more than one parent class.
2. Syntax and Structure
In Python, you can define a class that inherits from multiple parent classes by listing them in the class definition, separated by commas.
Example:
class Parent1: def method1(self): return "Parent1 method" class Parent2: def method2(self): return "Parent2 method" class Child(Parent1, Parent2): pass child = Child() print(child.method1()) # Output: Parent1 method print(child.method2()) # Output: Parent2 method
3. Method Resolution Order (MRO)
The Method Resolution Order (MRO) is the order in which Python looks for methods in a hierarchy of classes. It ensures that methods are called in the correct order when multiple inheritance is used.
Example:
class A: def method(self): return "A method" class B(A): def method(self): return "B method" class C(A): def method(self): return "C method" class D(B, C): pass d = D() print(d.method()) # Output: B method print(D.mro()) # Output: [, , , , ]
4. Diamond Problem
The diamond problem occurs when a class inherits from two classes that have a common ancestor. This can lead to ambiguity in method resolution.
Example:
class A: def method(self): return "A method" class B(A): pass class C(A): def method(self): return "C method" class D(B, C): pass d = D() print(d.method()) # Output: C method
5. Practical Applications
Multiple inheritance is useful in scenarios where a class needs to combine features from multiple existing classes. It allows for more flexible and modular code design.
Example:
class Flyable: def fly(self): return "Flying" class Swimmable: def swim(self): return "Swimming" class Duck(Flyable, Swimmable): def quack(self): return "Quack!" duck = Duck() print(duck.fly()) # Output: Flying print(duck.swim()) # Output: Swimming print(duck.quack()) # Output: Quack!