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

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

inheritance

If we define methods in the super class, we can use them in the sub class. In this example we define the method start() in the super class. An object created from the sub class can then use that method.

#!/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