Composition
Learn how to achieve composition in Python.
We'll cover the following
Composition is the practice of accessing other class objects in your class. In such a scenario, the class which creates the object of the other class is known as the owner and is responsible for the lifetime of that object.
Composition relationships are Part-of relationships where the part must constitute a segment of the whole object. We can achieve composition by adding smaller parts of other classes to make a complex unit.
But what makes composition so unique?
In composition, the lifetime of the owned object depends on the lifetime of the owner.
Example
A car
is composed of an engine, tires, and doors. In this case, a Car
owned these objects, so a Car
is an Owner class, and the tires
, doors
, and engine
classes are Owned classes.
Get hands-on with 1200+ tech skills courses.