Inheritance


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 Courses:

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.


22 thoughts on “Inheritance

  1. Anna Gao - July 12, 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.

    1. Frank - July 13, 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.

  2. Naveen Kerati - July 1, 2015

    how can we call super class functions in subclass

    1. Frank - July 1, 2015

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

  3. Leasinop - June 3, 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!

    1. Frank - June 3, 2015

      Thanks! More tutorials coming soon

  4. Zolaz - May 31, 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

    1. Frank - May 31, 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):
      Inheritance Python

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

      1. Naut - June 7, 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.

        1. Frank - June 7, 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()
      2. Chhavleen Singh - July 30, 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 ?

        1. Frank - July 31, 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.

  5. Anders Bregendahl - May 20, 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.

    1. Frank - May 20, 2015

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