
Python
Advanced inheritance includes multiple inheritance with proper MRO (Method Resolution Order), mixin classes for composing behavior, and cooperative methods using super(). These patterns enable flexible, reusable code architectures.
Mixins are small classes that provide specific functionality to be mixed into other classes. They solve the problem of needing multiple features without deep inheritance hierarchies.
class TimestampMixin:
"""Adds timestamp tracking"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.created_at = None
self.updated_at = None
class JSONSerializableMixin:
"""Adds JSON serialization"""
def to_json(self):
import json
return json.dumps(self.__dict__)
def from_json(self, json_str):
import json
data = json.loads(json_str)
for key, value in data.items():
setattr(self, key, value)
class ValidationMixin:
"""Adds validation"""
def validate(self):
for key, value in self.__dict__.items():
if value is None:
raise ValueError(f"{key} cannot be None")
class User(TimestampMixin, JSONSerializableMixin, ValidationMixin):
def __init__(self, name, email):
super().__init__()
self.name = name
self.email = email
user = User("Alice", "alice@example.com")
print(user.to_json())
user.validate()Properly implement multiple inheritance using super() for cooperative method calls.
class A:
def method(self):
print("A.method")
super().method()
class B:
def method(self):
print("B.method")
super().method()
class C:
def method(self):
print("C.method")
class D(A, B, C):
pass
d = D()
d.method()
# Output:
# A.method
# B.method
# C.method
print(D.mro())
# Shows the method resolution orderPython's MRO elegantly solves the diamond problem in multiple inheritance.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return f"{super().speak()} - Woof!"
class Cat(Animal):
def speak(self):
return f"{super().speak()} - Meow!"
class Pet(Dog, Cat):
"""Inherits from both Dog and Cat"""
pass
pet = Pet()
print(pet.speak())
# Output: Some sound - Woof!
# Not: Some sound - Woof! - Meow!
print(Pet.mro())
# [Pet, Dog, Cat, Animal, object]Combine ABCs with multiple inheritance for powerful interfaces.
from abc import ABC, abstractmethod
class Drawable(ABC):
@abstractmethod
def draw(self):
pass
class Resizable(ABC):
@abstractmethod
def resize(self, factor):
pass
class Rotatable(ABC):
@abstractmethod
def rotate(self, degrees):
pass
class Shape(Drawable, Resizable, Rotatable):
"""Abstract base combining multiple interfaces"""
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def draw(self):
return f"Drawing circle with radius {self.radius}"
def resize(self, factor):
self.radius *= factor
def rotate(self, degrees):
return "Circle doesn't change with rotation"
circle = Circle(5)
print(circle.draw())
circle.resize(2)
print(circle.draw())class LoggingMixin:
def log(self, message):
print(f"[LOG] {message}")
class MetricsMixin:
def record_metric(self, name, value):
if not hasattr(self, '_metrics'):
self._metrics = {}
self._metrics[name] = value
class CacheMixin:
def cache_result(self, key, result):
if not hasattr(self, '_cache'):
self._cache = {}
self._cache[key] = result
def get_cached(self, key):
if hasattr(self, '_cache'):
return self._cache.get(key)
return None
class DataProcessor(LoggingMixin, MetricsMixin, CacheMixin):
def process(self, data):
self.log(f"Processing {len(data)} items")
self.record_metric("items_processed", len(data))
self.cache_result("last_result", data)
return sum(data)
processor = DataProcessor()
result = processor.process([1, 2, 3, 4, 5])
print(f"Result: {result}")
print(f"Cached: {processor.get_cached('last_result')}")class RequestHandlerMixin:
def parse_request(self, data):
self.request_data = data
class ResponseBuilderMixin:
def build_response(self, status, body):
return {"status": status, "body": body}
class AuthenticationMixin:
def authenticate(self, token):
return len(token) > 0
class MiddlewareMixin:
def apply_middleware(self, handler):
self.middleware = handler
class APIEndpoint(RequestHandlerMixin, ResponseBuilderMixin,
AuthenticationMixin, MiddlewareMixin):
def handle_request(self, request, token):
self.parse_request(request)
if not self.authenticate(token):
return self.build_response(401, "Unauthorized")
return self.build_response(200, "Success")
endpoint = APIEndpoint()
response = endpoint.handle_request({"action": "get_users"}, "valid_token")
print(response)| Concept | Remember |
|---|---|
| Mixin | Reusable class providing specific functionality |
| Multiple Inheritance | Inherit from multiple parent classes |
| MRO | Method Resolution Order - controls method lookup |
| super() | Call parent methods in cooperative way |
| Diamond Problem | Multiple inheritance with shared ancestor |
| ABC | Abstract Base Class for enforcing interfaces |
| Composition over Inheritance | Often better than deep hierarchies |
| Interface Segregation | Small focused mixins |
Continue with advanced polymorphism patterns.
Ready to practice? Try challenges or explore more concepts
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward