Object-Oriented Programming in Python (Part 2): Inheritance

In the previous tutorial, you saw an introduction to Object-Oriented Programming using Python. It introduced you to the use of classes and class methods. Now to extend the knowledge you are going to learn about more things you can do using classes.


Inheritance provides a way of sharing functionality between classes. Imagine you had classes Cat, Dog and so on. They may be different in many ways, i.e. Dog might have the method bark, but the all have similar attributes like color and name. Instead to add a __init__ method for all classes which is rather redundant and will make our code messy when there is a lot of various objects inter related in our classes.

The similarity can be expressed by making them all inherit the super class Animal, which contains the shared functionality. To inherit a class form another class, put the super class name in parenthesis after the class name.

A class that inherits from another class is called a subclass. A class that is inherited from is called a super class.

NOTE: If a class inherits from another with the same attributes or methods, it overrides them.

The Function: Super

The function super is an inheritance related function that refers to the parent class. It is used to find the method with a certain name in the object’s super class.


Related Posts