Python inheritance and polymorphism

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

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!

Leave a Reply

15 Comments on "Python inheritance and polymorphism"

Notify of
avatar

Sort by:   newest | oldest | most voted
Shouvik Dutta Roy
Guest
Shouvik Dutta Roy
9 days 6 hours ago

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

sumanth
Guest
16 days 8 hours ago
class Father: def get_surname(self): print “hello” class Son(Father): pass class Daughter(Father): pass class HF: def get_surname(self): print “welcome” class Husband(HF,Daughter): def get_surname(self): super(Husband,self).get_surname(self) d = Daughter() d.get_surname() /////// 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.
Tim
Guest
Tim
1 month 28 days ago
Hi, 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 adding: But now the color is : Blue — Please also do some examples… Read more »
Savio Pereira
Guest
Savio Pereira
8 months 25 days ago

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

Vishal Tyagi
Guest
Vishal Tyagi
1 year 6 months ago
Hi, 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): super().__init__(radius) self.__diamtr = diamtr def getdiamtr(self): return self.__diamtr * self.getRadius() c = rec(6,9) print(c.getdiamtr()) print(c.getRadius())
wpDiscuz