Inheritance vs. Composition: Choose the Right Design Approach

In Python, inheritance is used when one class is a specialized version of another class. In the following example, the WholeMilk class represents a specific type of milk.

On the other hand, composition is used when one class forms a “has-a” relationship with another class. In the following example, the MilkTea class contains an instance of Milk as an attribute.

By using composition, the MilkTea class can use the functionalities of the Milk class without inheriting its attributes and methods. This design enables:

  • Substituting the milk implementation without impacting the MilkTea class.
  • Reusing the Milk class in other classes, such as Cake.
Scroll to Top