Python inheritance and polymorphism

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Inheritance allows programmer to create a general class first then later extend it to more specialized class. It also allows programmer to write better code.

Using inheritance you can inherit all access data fields and methods, plus you can add your own methods and fields, thus inheritance provide a way to organize code, rather than rewriting it from scratch.

In object-oriented terminology when class X  extend class Y , then Y  is called super class or base class and X  is called subclass or derived class. One more point to note that only data fields and method which are not private are accessible by child classes, private data fields and methods are accessible only inside the class.

Syntax to create a subclass is:

Let take an example to illustrate the point.

Expected Output:

here we have created base class Vehicle  and it’s subclass Car . Notice that we have not defined getName()  in Car  class but we are still able to access it, because class Car  inherits it from Vehicle  class. In the above code super()  method is used to call method of the base class. Here is the how super()  works

Suppose you need to call a method called get_information()  in the base class from child class , you can do so using the following code.

similarly you can call base class constructor from child class constructor using the following code.

Multiple inheritance

Unlike languages like Java and C#, python allows multiple inheritance i.e you can inherit from multiple classes at the same time like this,

Let’s take an example:

Expected Output:

As you can see becuase ChildClass  inherited MySuperClass1 , MySuperClass2 , object of ChildClass  is now able to access method_super1()  and method_super2() .

Overriding methods

To override a method in the base class, sub class needs to define a method of same signature. (i.e same method name and same number of parameters as method in base class).

Expected Output:

Here we are overriding m1()  method from the base class. Try commenting m1()  method  in B  class and now m1()  method from Base class i.e class A  will run.

Expected Output:

isinstance() function

isinstance()  function is used to determine whether the object is an instance of the class or not.

Syntax: isinstance(object, class_type)

Next chapter Exception Handling.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

17 thoughts on “Python inheritance and polymorphism

  1. Vishal Tyagi


    I am running the below code and it always errors out. Can you point where and what it is that I am doing wrong:

    import math

    class Circle:

    def __init__(self, radius):
    self.__radius = radius

    def getRadius(self):
    return self.__radius

    def setRadius(self, radius):
    self.__radius = radius

    def area(self):
    return math.pi * self.__radius ** 2

    def __add__(self, another_circle):
    return Circle( self.__radius + another_circle.__radius )

    class rec(Circle):

    def __init__(self,radius, diamtr):
    self.__diamtr = diamtr

    def getdiamtr(self):
    return self.__diamtr * self.getRadius()

    c = rec(6,9)

      1. Vishal Tyagi

        Thanks for your response. But did the code yield you any results? As it still gives me error:

        Traceback (most recent call last):
        File “”, line 30, in
        c = rec(6,9)
        File “”, line 23, in __init__
        TypeError: super() takes at least 1 argument (0 given)

          1. admin Post author

            This tutorial is using python 3.4 try running your code in 3.4 and see if it works.

  2. Savio Pereira

    I am using Python 2.7 and I get the following error when using the ‘super()’ method: TypeError: super() argument 1 must be type, not classobj

    I was using the super() method with two arguments .

    super (ChildClass, self).__init__()

    I had to change my Base Class Vehicle to a new style class (Link) by declaring it as:

    class Vehicle(object):

    Only then did the super() method work. I am wondering how it worked for you. Has it got to do with the version of Python

  3. Tim

    Any reason that this method is in the Vehicle class? I guess this method is to override object color from red to new override color ‘Blue’? Can you add some more example in the code?

    def setColor(self, color): # setColor is accessible outside the class
    self.__color = color

    I tried to add this code in method, def getDescription(self)
    self.getColor() = self.setColor()

    and got :
    SyntaxError: can’t assign to function call (, line 27)

    in your example, the output is :
    Ford MustangGT350 in red color
    But now the color is : Blue

    Please also do some examples and explanation of this. is the method get_information() in the Vehicle class? or is it in car class? and be accessed by car class?

    ” Suppose you need to call a method called get_information() in the base class from child class , you can do so using the following code.
    super().get_information() ”


  4. sumanth

    class Father:
    def get_surname(self):
    print “hello”
    class Son(Father):

    class Daughter(Father):

    class HF:
    def get_surname(self):
    print “welcome”

    class Husband(HF,Daughter):
    def get_surname(self):

    d = Daughter()

    here in this program if i call d = Daughter() i should get the ans as (welcome)
    is it possible without modifying the first three classes.
    if possible pls send the code.

  5. Shouvik Dutta Roy

    Sir m a beginner, m facing a problem to call the function from child class
    import superclass

    class subclass(superclass.superclass)
    def __init__(object,variable, variable)
    def method1

    I want to call the method1 from another file by importing the subclass which will indirectly import the superclass, followed that the variable in __init__ function undre subclass have same name and working as that of the superclass. I created a object for the subclass as:
    s=subclass.subclass(variable, variable)

    then wanted to call the method1 using the object ‘s’ but it did not work, please help

  6. GeorRge

    Good article pratice for learning overloading constructor in child class , will insert super() every time because for pointer this ( self ) go back to point parent class

  7. Jazzy


    May i know what’s the error in this

    class Vehicle:

        def init(self, name, color):
            self.__name = name      
    self.__color = color

        def getColor(self):         # getColor() function is accessible to class Car
            return self.__color

        def setColor(self, color):  # setColor is accessible outside the class
            self.__color = color

        def getName(self): # getName() is accessible outside the class
            return self.__name

    class Car(Vehicle):

        def init(self, name, color, model):
    # call parent constructor to set name and color
            super().init(name, color)  
            self.__model = model

        def getDescription(self):
            return self.getName() + self.__model + ” in ” + self.getColor() + ” color”

    in method getDescrition we are able to call getName(), getColor() because they are

    accessible to child class through inheritance

    c = Car(“Ford Mustang”, “red”, “GT350”)
    print(c.getName()) # car has no method getName() but it is accessible through class Vehicle

    File “”, line 3
    def init(self, name, color):
    SyntaxError: invalid character in identifier


Leave a Reply

Your email address will not be published. Required fields are marked *