Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

Inheritance

Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.

Classes can inherit functionality of other classes. If an object is created using a class that inherits from a superclass, the object will contain the methods of both the class and the superclass. The same holds true for variables of both the superclass and the class that inherits from the super class.

Python supports inheritance from multiple classes, unlike other popular programming languages.

Related Course:
Practice Python with interactive exercises

Intoduction

We define a basic class named User:

class User:
    name = ""
    
    def __init__(self, name):
        self.name = name
    
    def printName(self):
        print("Name  = " + self.name)
    
brian = User("brian")
brian.printName()

This creates one instance called brian which outputs its given name. We create another class called Programmer.

class Programmer(User):

def __init__(self, name): self.name = name

def doPython(self): print("Programming Python")

This looks very much like a standard class except than User is given in the parameters. This means all functionality of the class User is accessible in the Programmer class.

Inheritance example

Full example of Python inheritance:

class User:
    name = ""
    
    def __init__(self, name):
        self.name = name

def printName(self): print("Name = " + self.name)

class Programmer(User): def __init__(self, name): self.name = name

def doPython(self): print("Programming Python")

brian = User("brian") brian.printName()

diana = Programmer("Diana") diana.printName() diana.doPython()

The output:

Name  = brian
Name  = Diana
Programming Python

Brian is an instance of User and can only access the method printName. Diana is an instance of Programmer, a class with inheritance from User, and can access both the methods in Programmer and User.

BackNext

Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises