Concept of Inheritance, Composition, and Aggregation in Python

Dinesh Madhup
2 min readJul 26, 2020

--

How to implement Inheritance, Composition, and Aggregation in Python?

Inheritance

Wikipedia: In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation.

Let me elaborate it in terms of computer science. You will see the below code that contains two classes. One is Person and other is Student, where class Student has all data members which Person has but not the vice-versa. Moreover, Class Student has one more feature or data-member named gradYear which is not present in Person.

So, simply we can say that it establishes an “is-a” or “kind of” relationship between Student and Person class. Saying that, Student is a kind of Person.

Composition

In composition one class acts as a container of the other class (contents). If you destroy the container there is no existence of contents. That means if the container class creates an object or hold an object of contents.

Composition established “has-a” relationship between objects. In below code, you can see that the class person is creating a heart object. So, person is the owner of the heart object. We can also say that Person and Heart objects are tightly coupled.

Aggregation

Not to confuse, aggregation is a form of composition where objects are loosely coupled. There are not any objects or classes owns another object. It just creates a reference. It means if you destroy the container, the content still exists.

In below code, Person just reference to Heart. There is no tight coupling between Heart and Person object.

Hope You Enjoyed Reading. Happy Coding!!!

--

--