python logo

python class inheritance


Python hosting: Host, run, and code Python in the cloud!

Python offers a robust paradigm of object-oriented programming, allowing classes to inherit functionality from other classes. This enables objects that are created using a class inheriting from a superclass to have access to methods and variables of both the superclass and the derived class. Unlike some other languages, Python even supports multiple inheritance, expanding its utility.

Related Course: Python Programming Bootcamp: Go from zero to hero

Understanding Basic Inheritance

Consider a foundational 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()

Here, we’ve crafted an instance named brian that simply displays the name provided to it. Building on this, let’s design another class, Programmer.

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

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

At first glance, the Programmer class mirrors a conventional class. However, the inclusion of User as a parameter indicates that Programmer inherits all functionalities from the User class.

Demonstrating Inheritance

Here’s a comprehensive demonstration of inheritance in Python:

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()

When executed, the code will produce:

Name  = brian
Name = Diana
Programming Python

Through this example, it becomes evident that while brian, an instance of User, can only invoke the printName method, diana, stemming from the Programmer class, can utilize methods from both User and Programmer due to the inheritance.

Practice your skills: Download Exercises
← Previous Topic | Next Topic →






Leave a Reply:




Anders Bregendahl Wed, 20 May 2015

In the first example, i think there should be a 'self' in the arguments for the 'doPython' function, as for me it gives an error, if this is not the case. I'm using Python 3.4.3 btw.

Frank Wed, 20 May 2015

Thanks! Yes, you are correct. This is shown in the example doPython function call right below. I updated it.

Zolaz Sun, 31 May 2015

Hello, is it necessary to redefine the __init__ function in the second class ( Programmer ) since it already exist in the mother class ? It looked weird to me so I took it off and it still worked ? Will it become some kind of a problem later ? Thank you so much for this tutorial

Frank Sun, 31 May 2015

That's a good question. Both options should work and there shouldn't be any problems. Its a decision you as programmer have to make depending on what you are making.

The __init__ function is often called constructor. If we give the Programmer class an __init__ function, a new Programmer object will use that function on creation. Otherwise it will use the inherited constructor of the User class.

However, in both cases the functions will be inherited from the user class. That is to say, all functions from User will be available unless you explicitly define __init__.

A visual representation of what's going on (left: classes, right: objects):
https://pythonspot.com/wp-c..." alt="Inheritance Python" width="97%"/>

If you have any more questions let me know. I hope you enjoy my site, more tutorials will follow :-)

Leasinop Wed, 03 Jun 2015

This web is great. I come from C/C++ and wished I found something as clear while learning it. You're cool in your explanations, simple and effective. Keep it up!

Frank Wed, 03 Jun 2015

Thanks! More tutorials coming soon

Naut Sun, 07 Jun 2015

Hello Frank, Great site! building on Zolaz's question, is there a way to extend the functionality achieved by the constructor of the User class without having to re-write the common parts?

For instance, if I were to have a new element inside the Programmer class (say numberOfLanguagesKnown). I would want to additionally initialise only the new variable that is not already a part of the User class without having to replicate the Users constructor in full. Is it possible? Hope my question is clear.

Frank Sun, 07 Jun 2015

Hi Naut, thank you! In Python you can not partially inherit a constructor, it's either the constructor of Programmer or User. You can however set object variables after creation with a setter function:

class User:
name = ""

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

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

class Programmer(User):
numberOfLanguagesKnown = 0

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

def setLang(self,amount):
self.numberOfLanguagesKnown = amount

def doPython(self):
print "Programming Python"

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

diana = Programmer("Diana")
diana.setLang(2)
diana.printName()
diana.doPython()
Naveen Kerati Wed, 01 Jul 2015

how can we call super class functions in subclass

Frank Wed, 01 Jul 2015

Hi, do you mean in inheritance or inner classes? When using inheritance you can directly call the methods.

Anna Gao Sun, 12 Jul 2015

Hi, Frank, I'm new to Python, coming from Matlab. I'm a little confused about running different files. In this class case, can I write the two classes in two different files? It seems that I need to run the mother class User before the child class Programmer.

In Matlab, I can use a function I wrote in any places as long as the function file is in the directory. Python seems cannot "remember" the functions I wrote? I am very confused with this problem.

Frank Mon, 13 Jul 2015

Hi Anna, yes you can have a one class for each file. The Programmer class/file should then import the User class. This is a common practice in Python

Python behaves different from Matlab in that regard: Python does not search for files/functions in a directory, you have to explicitly specify the file with the line 'import'. This means you would 'from user import *' or 'import user'. If you have a file with functions (myfunctions.py) you could simply do 'from myfunctions import *'. A single class or file may contain hundreds of functions.

Chhavleen Singh Thu, 30 Jul 2015

You wrote "If we give the Programmer class an __init__ function, a new Programmer object will use that function on creation. Otherwise it will use the inherited constructor of the User class.". I want to know, if we give constructor to Programmer class and create a object of Programmer class. So, it will use constructor of Programmer class for sure. Will it use constructor of 'Inherited' User class. If yes, then what will be the flow ?

Chhavleen Singh Thu, 30 Jul 2015

How many types of Inheritance is supported by Python ? Is there any feature of abstract class or interface in Python ? I am from JAVA background. Thanks.

Siva Fri, 31 Jul 2015

why do we have to define again the constructor in the inherited class Programmer??

Frank Fri, 31 Jul 2015

It depends on your version. Python version 2.6 and later have Abstract Base Classes.
Unlike Java, Python supports multiple inheritance:

#!/usr/bin/env python

class ClassA( object ):
def sayA( self ):
print('say A')

class ClassB( object ):
def sayB( self ):
print('say B')

class Concrete( ClassA, ClassB ):
pass


c = Concrete()
c.sayA()
c.sayB()

Frank Fri, 31 Jul 2015

On top of my head: If a Programmer class with constructor is defined, a new instance of the class Programmer will use that constructor regardless of whether or not it inherits from another class. That means, the inherited constructor will simply be overwritten.

Frank Fri, 31 Jul 2015

This is optional. You may want to create a new Programmer object which inherits from another class, but have specific behavior in the constructor.

Sheik Sun, 02 Aug 2015

Hi Frank,

My Question related to one of the previous question by a friend 'Anna Gao'.
What is the difference between 'import user' and 'from user import *'?

I am getting a following error when I create a sub class with string parameter (even though the base class also of same type) with 'import user' but works fine with 'from user import *'

NameError: name 'User' is not defined

Frank Sun, 02 Aug 2015

'imports X' imports the module. You can use X.name to access the variables.
'from X import *' imports the module X you can access all publics directly.

Manuel Giron Mon, 17 Aug 2015

Hi!, I have a question, how can I declare X number of variables in the Programmer Class, and set them when getting the instance of it. for example I want to set the programming language in the Programmer Class extending all the other parameters of the User Class.

Frank Mon, 17 Aug 2015

The traditional way is to use setter functions, in this example we have the variable name from the user class while also having language from the programmer class:


class User:
name = ""

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

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

class Programmer(User):

language = ""

def setLanguage(self, language):
self.language = language

def printLanguage(self):
print self.language

manuel = Programmer("Manuel")
manuel.setLanguage("Python")
manuel.printName()
manuel.printLanguage()

A more detailed example, where variables from the User class and Programmer class are used:

class User:
name = None
job = None

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

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

def printJob(self):
print "Job = " + self.job

class Programmer(User):

language = ""

def setLanguage(self, language):
self.language = language

def printLanguage(self):
print "Language = " + self.language

guido = Programmer("Guido","Developer")
guido.setLanguage("Python")
guido.printName()
guido.printLanguage()
guido.printJob()

An instance can be created only from one class, thus either the Programmer class or User class. If we overwrite the User constructor, we can no longer access its variables, thus we have to pick one constructor. If we pick the Programmers constructor we would have:

class User:
name = None
job = None

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

def setJob(self,job):
self.job = job

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

def printJob(self):
print "Job = " + self.job

class Programmer(User):

language = ""

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

def printLanguage(self):
print "Language = " + self.language

guido = Programmer("Python")
guido.setName("Guido")
guido.setJob("Developer")
guido.printName()
guido.printLanguage()
guido.printJob()

To set multiple variables you can either pass a list/tuple to an setter function or define various setter functions and call them one by one. I hope that helps, let me know if you have any questions