Python Multiple Inheritance & Mixins
OOP Architecture
Multiple Inheritance & Mixins
Python allows a class to inherit from multiple bases. Learn when to embrace it and how to avoid the dreaded diamond problem.
Mixins
- Lightweight classes that provide reusable methods but no state.
- Naming convention:
SomethingMixin. - Example:
from datetime import datetime, timezone
class TimestampMixin:
def touch(self):
self.created_at = datetime.now(timezone.utc)
class AuditedModel(TimestampMixin, BaseModel):
...
Best practices
- Keep mixins focused on a single behavior.
- Ensure cooperative
super()calls so each parent runs. - Document expected attributes/methods that mixins rely on.