Skip to content

Instantly share code, notes, and snippets.

@rednafi
Last active August 22, 2020 06:38
Show Gist options
  • Save rednafi/517e3fcc169a8e4f50b1a27ee3500afa to your computer and use it in GitHub Desktop.
Save rednafi/517e3fcc169a8e4f50b1a27ee3500afa to your computer and use it in GitHub Desktop.
Inheritance-like auto delegation via composition in Python
from typing import Dict, Any
class Engine:
def __init__(self, name: str, sound: str) -> None:
self.name = name
self.sound = sound
def noise(self) -> str:
return f"Engine {self.name} goes {self.sound}!"
class Bugatti:
def __init__(self, engine: Engine, tier: str, price: int) -> None:
self.engine = engine
self.tier = tier
self.price = price
def info(self) -> Dict[str, Any]:
return {"tier": self.tier, "price": self.price}
def __getattr__(self, attr: str) -> Any:
return getattr(self.engine, attr)
if __name__ == "__main__":
engine = Engine("w16", "vroom")
chiron = Bugatti(engine, "supercar", 3_000_000)
assert chiron.info() == {"tier": "supercar", "price": 3000000}
assert chiron.noise() == "Engine w16 goes vroom!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment