Practical super() Examples
Real-World Inheritance Scenarios
1. Game Character Class Hierarchy
class Character:
def __init__(self, name, health):
self.name = name
self.health = health
def attack(self):
print(f"{self.name} performs basic attack")
class Warrior(Character):
def __init__(self, name, health, strength):
super().__init__(name, health)
self.strength = strength
def attack(self):
super().attack()
print(f"Warrior {self.name} deals powerful strike")
class Mage(Character):
def __init__(self, name, health, mana):
super().__init__(name, health)
self.mana = mana
def attack(self):
super().attack()
print(f"Mage {self.name} casts magical spell")
Complex Inheritance Patterns
2. Multilevel Inheritance with Configuration
class DatabaseConfig:
def __init__(self, host='localhost'):
self.host = host
class SQLDatabase(DatabaseConfig):
def __init__(self, host, database):
super().__init__(host)
self.database = database
def connect(self):
print(f"Connecting to {self.database} at {self.host}")
class PostgreSQLDatabase(SQLDatabase):
def __init__(self, host, database, port=5432):
super().__init__(host, database)
self.port = port
def connect(self):
super().connect()
print(f"Using port {self.port}")
Cooperative Multiple Inheritance
3. Plugin-Based System
class LoggerMixin:
def log(self, message):
print(f"[LOG] {message}")
class NetworkMixin:
def send_data(self, data):
print(f"Sending data: {data}")
class DataProcessor(LoggerMixin, NetworkMixin):
def process(self, data):
super().log("Starting data processing")
## Process data
super().send_data(data)
super().log("Data processing complete")
Method Resolution Order Visualization
graph TD
A[Base Class] --> B[Mixin 1]
A --> C[Mixin 2]
B --> D[Final Class]
C --> D
Practical Inheritance Patterns
Pattern |
Use Case |
super() Benefit |
Single Inheritance |
Basic class extension |
Simple method calling |
Multiple Inheritance |
Mixing behaviors |
Flexible method resolution |
Composition |
Delegating functionality |
Avoid deep inheritance |
Best Practices
- Use
super()
consistently
- Understand Method Resolution Order
- Keep inheritance hierarchies shallow
- Prefer composition over deep inheritance
Common Anti-Patterns to Avoid
- Excessive multiple inheritance
- Deep, complex inheritance trees
- Overusing
super()
without clear purpose
By mastering these practical examples, developers can leverage super()
to create more flexible and maintainable Python class hierarchies.