Advanced Inheritance
Multiple inheritance, MRO, mixins, and composition patterns.
Overview
Master advanced inheritance patterns.
Multiple Inheritance
class Flying:
def fly(self):
return "Flying"
class Swimming:
def swim(self):
return "Swimming"
class Duck(Flying, Swimming):
def quack(self):
return "Quack"
duck = Duck()
print(duck.fly()) # Flying
print(duck.swim()) # Swimming
print(duck.quack()) # Quack
Method Resolution Order
class A:
def method(self):
print("A.method")
class B(A):
def method(self):
print("B.method")
class C(A):
def method(self):
print("C.method")
class D(B, C):
pass
d = D()
d.method() # B.method (MRO: D -> B -> C -> A -> object)
print(D.__mro__)
Mixins
import json
class JSONMixin:
def to_json(self):
return json.dumps(self.__dict__)
@classmethod
def from_json(cls, json_str):
data = json.loads(json_str)
return cls(**data)
class User(JSONMixin):
def __init__(self, name, email):
self.name = name
self.email = email
user = User("Alice", "alice@example.com")
json_str = user.to_json()
print(json_str) # {"name": "Alice", "email": "alice@example.com"}
user2 = User.from_json(json_str)
print(user2.name) # Alice
Composition
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
return "Engine started"
class Car:
def __init__(self, make, model, horsepower):
self.make = make
self.model = model
self.engine = Engine(horsepower)
def start(self):
return f"{self.make} {self.model}: {self.engine.start()}"
car = Car("Toyota", "Camry", 200)
print(car.start()) # Toyota Camry: Engine started
Practice
Design a game character system using mixins and composition.