Inheritance means extending the properties of one class by another. Inheritance implies code reusability, because client classes does not need to implement everything from scratch. They can simply refer to their base classes to execute the code.

Unlike Java and C#, like C++, Python allows Multiple inheritance. Name resolution is done by the order in which base classes are specified.


class ClassName(BaseClass1[,BaseClass2,....,BaseClassN]):
    <statement 0>
    <statement 1>
    <statement 2>
    <statement n>

A First Example

In [3]:
class Person:

    # Constructor
    def __init__(self, name,age): = name
        self.age = age

    def __str__(self):
        return 'name = {}\nage = {}'.format(,self.age)

# Inherited or Sub class
class Employee(Person):

    def __init__(self,name,age,employee_id):
        Person.__init__(self,name,age) # Referring Base class
        # Also be done by super(Employee,self).__init__(name,age)
        self.employee_id = employee_id

    # Overriding implied code reusability
    def __str__(self):
        return Person.__str__(self) + '\nemployee id = {}'.format(self.employee_id)
In [4]:
s = Person('Kiran',18)
name = Kiran
age = 18
In [6]:
e = Employee('Ramesh',18,48)
name = Ramesh
age = 18
employee id = 48


Base class can be referred from derived class in two ways

  • Base Class name - BaseClass.function(self,args)
  • using super() - super(self,DerivedClass).function(args)

Multiple inheritance and Order of Invocation of Methods

In [7]:
class Base1:
    def some_method(self):

class Base2:
    def some_method(self):

class Derived1(Base1,Base2):

class Derived2(Base2,Base1):

Note how pass statement is used to leave the class body empty. Otherwise it would have raised a Syntax Error. Since Drived1 and Derived2 are empty, they would have imported the methods from their base classes

In [8]:
d1 = Derived1()
d2 = Derived2()

Now what will be the result of invoking some_method on d1 and d2? … Does the name clash ocuur? … Let’s see

In [9]:
In [10]:

Wow! … It executed smoothly …

If a name of a function is same in base classes, the one will be executed, which appears first in the base class list