Inheritance: A class can get the properties and variables of another class. This class is called the super class or parent class.

Inheritances saves you from repeating yourself (in coding: dont repeat yourself), you can define methods once and use them in one or more subclasses.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Introduction

You need at least two classes for inheritance to work. Like real life, one will inherit from the other.
The class that inherits from the super class, will get everything. What’s everything?

In the case of object oriented programming that means it will get the methods and variables from the super class.

Multiple classes can inherit from the same super class. In such case all of sub classes will get all of the properties and methods of the super class.

inheritance

How it works

Define two classes, one super class (App) and one sub class (Android). The sub class (Android) inherits from the class App.

First we define the super class. The super class is written just like a normal class, there’s nothing special about it except that others will inherit from it. You can give it methods and variables if you want.

class App:
def start(self):
print('starting')

We defined methods and variables in the super class (App), once inherited we can use them in the sub class. Let’s create a class (Android) that inherits from the super class.

In the super class we create the method start(). This is just for demonstration purpose, the method will be usable when creating an object with the class Android.

How does Python know a class wants to inherit? The braces after it with the class name.

class Android(App):

First the normal class name is defined, the super class is defined after that.

Code Example

The example below is a demonstration of inheritance in Python. Python supports multiple inheritance, but in this example we inherit from only one super class.

Complete example below:

#!/usr/bin/python

class App:
def start(self):
print('starting')

class Android(App):
def getVersion(self):
print('Android version')

app = Android()
app.start()
app.getVersion()

Exercises

Try the exercises below:

  1. Create a new class that inherits from the class App
  2. Try to create a class that inherits from two super classes (multiple inheritance)

Download answers