Lesson 15: Composition vs inheritance
A car has an engine — but it isn't a kind of engine. For "has-a" relations there's a second tool, surprisingly simple: store one object as another object's attribute. That's composition — and choosing between it and inheritance is one of design's key decisions.
Inheritance is DNA — what you are; composition is a backpack — what you have. A dog is an animal (inheritance), but a car merely has an engine (composition).
- composition
- Building a class out of other classes' objects — an object stored as an attribute: self.engine = Engine().
- the has-a relation
- "A car has an engine" — a relation solved with composition, not inheritance.