Advanced Inheritance Patterns
Multiple Inheritance
Multiple inheritance allows a class to inherit from multiple parent classes simultaneously.
class Engine:
def start(self):
print("Engine started")
class ElectricSystem:
def charge(self):
print("Charging battery")
class HybridCar(Engine, ElectricSystem):
def __init__(self, model):
self.model = model
def operate(self):
self.start()
self.charge()
## Demonstration
hybrid = HybridCar("Toyota Prius")
hybrid.operate()
Method Resolution Order (MRO)
graph TD
A[Base Class A] --> C[Multiple Inheritance Class]
B[Base Class B] --> C
D[Base Class C] --> C
MRO Rules
Rule |
Description |
C3 Linearization |
Determines method call sequence |
__mro__ Attribute |
Shows inheritance hierarchy |
super() |
Navigates method resolution path |
Composition over Inheritance
class Battery:
def charge(self):
print("Battery charging")
class Motor:
def run(self):
print("Motor running")
class ElectricVehicle:
def __init__(self):
self.battery = Battery()
self.motor = Motor()
def operate(self):
self.battery.charge()
self.motor.run()
Abstract Base Classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
Mixin Classes
class LoggerMixin:
def log(self, message):
print(f"[LOG] {message}")
class DatabaseHandler(LoggerMixin):
def save_data(self, data):
self.log("Saving data")
## Database saving logic
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class DatabaseConnection(metaclass=SingletonMeta):
def __init__(self):
self.connection = None
Advanced Inheritance Techniques
- Dependency Injection
- Composition Patterns
- Interface Implementation
- Dynamic Class Creation
- Minimize deep inheritance hierarchies
- Prefer composition when possible
- Use
__slots__
for memory optimization
Best Practices
- Keep inheritance simple and meaningful
- Follow SOLID principles
- Document inheritance relationships
LabEx recommends mastering these advanced patterns to write more flexible and maintainable Python code.