Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation to
the functions of the parent class. In this section of the tutorial, we will discuss inheritance in
detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name. Consider the following syntax to inherit a base class into the derived
class.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
PauseNext
Mute
Current Time 0:41
/
Duration 18:10
Loaded: 9.54%
Fullscreen
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. [Link]()
10. [Link]()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level
inheritance is archived when a derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi-level inheritance is archived in python.
The syntax of multi-level inheritance is given below.
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. [Link]()
14. [Link]()
15. [Link]()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below.
Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print([Link](10,20))
12. print([Link](10,20))
13. print([Link](10,20))
Output:
30
200
0.5
The is subclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the specified classes.
It returns true if the first class is the subclass of the second class, and false otherwise.
Consider the following example.
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))
Output:
True
False
The is instance (obj, class) method
The isinstance() method is used to check the relationship between the objects and classes. It
returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.
Consider the following example.
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific implementation,
then the concept is called method overriding. We may need to perform method overriding in the
scenario where the different definition of a parent class method is needed in the child class.
Consider the following example to perform method overriding in python.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
[Link]()
Output:
Barking
Real Life Example of method overriding
1. class Bank:
2. def getroi(self):
3. return 10;
4. class SBI(Bank):
5. def getroi(self):
6. return 7;
7.
8. class ICICI(Bank):
9. def getroi(self):
10. return 8;
11. b1 = Bank()
12. b2 = SBI()
13. b3 = ICICI()
14. print("Bank Rate of interest:",[Link]());
15. print("SBI Rate of interest:",[Link]());
16. print("ICICI Rate of interest:",[Link]());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
Data abstraction in python
Abstraction is an important aspect of object-oriented programming. In python, we can also
perform data hiding by adding the double underscore (___) as a prefix to the attribute which is to
be hidden. After this, the attribute will not be visible outside of the class through the object.
Consider the following example.
Example
1. class Employee:
2. __count = 0;
3. def __init__(self):
4. Employee.__count = Employee.__count+1
5. def display(self):
6. print("The number of employees",Employee.__count)
7. emp = Employee()
8. emp2 = Employee()
9. try:
10. print(emp.__count)
11. finally:
12. [Link]()
Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
Python Inheritance
Being an object-oriented language, Python supports class inheritance. It allows us
to create a new class from an existing one.
The newly created class is known as the subclass (child or derived class).
The existing class from which the child class inherits is known as the superclass
(parent or base class).
Python Inheritance Syntax
# define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Here, we are inheriting the sub_class from the super_class .
Note: Before you move forward with inheritance, make sure you know
how Python classes and objects work.
Example: Python Inheritance
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", [Link])
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
[Link] = "Rohu"
[Link]()
# call subclass method
[Link]()
Run Code
Output
I can eat
My name is Rohu
In the above example, we have derived a subclass Dog from a superclass Animal .
Notice the statements,
[Link] = "Rohu"
[Link]()
Here, we are using labrador (object of Dog ) to access name and eat() of
the Animal class.
This is possible because the subclass inherits all attributes and methods of the
superclass.
Also, we have accessed the name attribute inside the method of the Dog class
using self .
Python Inheritance Implementation
is-a relationship
Inheritance is an is-a relationship. That is, we use inheritance only if there exists
an is-a relationship between two classes. For example,
Car is a Vehicle
Apple is a Fruit
Cat is an Animal
Here, Car can inherit from Vehicle, Apple can inherit from Fruit, and so on.
Method Overriding in Python Inheritance
In the previous example, we see the object of the subclass can access the method of
the superclass.
However, what if the same method is present in both the superclass and
subclass?
In this case, the method in the subclass overrides the method in the superclass. This
concept is known as method overriding in Python.
Example: Method Overriding
class Animal:
# attributes and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# override eat() method
def eat(self):
print("I like to eat bones")
# create an object of the subclass
labrador = Dog()
# call the eat() method on the labrador object
[Link]()
Run Code
Output
I like to eat bones
What is Inheritance in Python?
Inheritance is one of the most important features of object-oriented programming languages
like Python. It is used to inherit the properties and behaviours of one class to another. The
class that inherits another class is called a child class and the class that gets inherited is called
a base class or parent class.
If you have to design a new class whose most of the attributes are already well defined in an
existing class, then why redefine them? Inheritance allows capabilities of existing class to be
reused and if required extended to design a new class.
Inheritance comes into picture when a new class possesses 'IS A' relationship with an existing
class. For example, Car IS a vehicle, Bus IS a vehicle, Bike IS also a vehicle. Here, Vehicle is
the parent class, whereas car, bus and bike are the child classes.
Creating a Parent Class
The class whose attributes and methods are inherited is called as parent class. It is defined
just like other classes i.e. using the class keyword.
Syntax
The syntax for creating a parent class is shown below −
class ParentClassName:
{class body}
Creating a Child Class
Classes that inherit from base classes are declared similarly to their parent class, however, we
need to provide the name of parent classes within the parentheses.
Syntax
Following is the syntax of child class −
class SubClassName (ParentClass1[, ParentClass2, ...]):
{sub class body}
Types of Inheritance
In Python, inheritance can be divided in five different categories −
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Python - Single Inheritance
This is the simplest form of inheritance where a child class inherits attributes and methods
from only one parent class.
Example
The below example shows single inheritance concept in Python −
Open Compiler
# parent class
class Parent:
def parentMethod(self):
print ("Calling parent method")
# child class
class Child(Parent):
def childMethod(self):
print ("Calling child method")
# instance of child
c = Child()
# calling method of child class
[Link]()
# calling method of parent class
[Link]()
On running the above code, it will print the following result −
Calling child method
Calling parent method
Python - Multiple Inheritance
Multiple inheritance in Python allows you to construct a class based on more than one parent
classes. The Child class thus inherits the attributes and method from all parents. The child can
override methods inherited from any parent.
Syntax
class parent1:
#statements
class parent2:
#statements
class child(parent1, parent2):
#statements
Example
Python's standard library has a built-in divmod() function that returns a two-item tuple. First
number is the division of two arguments, the second is the mod value of the two operands.
This example tries to emulate the divmod() function. We define two classes division and
modulus, and then have a div_mod class that inherits them.
class division:
def __init__(self, a,b):
self.n=a
self.d=b
def divide(self):
return self.n/self.d
class modulus:
def __init__(self, a,b):
self.n=a
self.d=b
def mod_divide(self):
return self.n%self.d
class div_mod(division,modulus):
def __init__(self, a,b):
self.n=a
self.d=b
def div_and_mod(self):
divval=[Link](self)
modval=modulus.mod_divide(self)
return (divval, modval)
The child class has a new method div_and_mod() which internally calls the divide() and
mod_divide() methods from its inherited classes to return the division and mod values.
x=div_mod(10,3)
print ("division:",[Link]())
print ("mod_division:",x.mod_divide())
print ("divmod:",x.div_and_mod())
Output
division: 3.3333333333333335
mod_division: 1
divmod: (3.3333333333333335, 1)
Method Resolution Order (MRO)
The term method resolution order is related to multiple inheritance in Python. In Python,
inheritance may be spread over more than one levels. Let us say A is the parent of B, and B
the parent for C. The class C can override the inherited method or its object may invoke it as
defined in its parent. So, how does Python find the appropriate method to call.
Each Python has a mro() method that returns the hierarchical order that Python uses to
resolve the method to be called. The resolution order is from bottom of inheritance order to
top.
In our previous example, the div_mod class inherits division and modulus classes. So, the
mro method returns the order as follows −
[<class '__main__.div_mod'>, <class '__main__.division'>, <class '__main__.modulus'>,
<class 'object'>]
Python - Multilevel Inheritance
In multilevel inheritance, a class is derived from another derived class. There exists multiple
layers of inheritance. We can imagine it as a grandparent-parent-child relationship.
Example
In the following example, we are illustrating the working of multilevel inheritance.
Open Compiler
# parent class
class Universe:
def universeMethod(self):
print ("I am in the Universe")
# child class
class Earth(Universe):
def earthMethod(self):
print ("I am on Earth")
# another child class
class India(Earth):
def indianMethod(self):
print ("I am in India")
# creating instance
person = India()
# method calls
[Link]()
[Link]()
[Link]()
When we execute the above code, it will produce the following result −
I am in the Universe
I am on Earth
I am in India
Python - Hierarchical Inheritance
This type of inheritance contains multiple derived classes that are inherited from a single base
class. This is similar to the hierarchy within an organization.
Example
The following example illustrates hierarchical inheritance. Here, we have defined two child
classes of Manager class.
Open Compiler
# parent class
class Manager:
def managerMethod(self):
print ("I am the Manager")
# child class
class Employee1(Manager):
def employee1Method(self):
print ("I am Employee one")
# second child class
class Employee2(Manager):
def employee2Method(self):
print ("I am Employee two")
# creating instances
emp1 = Employee1()
emp2 = Employee2()
# method calls
[Link]()
emp1.employee1Method()
[Link]()
emp2.employee2Method()
On executing the above program, you will get the following output −
I am the Manager
I am Employee one
I am the Manager
I am Employee two
Python - Hybrid Inheritance
Combination of two or more types of inheritance is called as Hybrid Inheritance. For
instance, it could be a mix of single and multiple inheritance.
Example
In this example, we have combined single and multiple inheritance to form a hybrid
inheritance of classes.
Open Compiler
# parent class
class CEO:
def ceoMethod(self):
print ("I am the CEO")
class Manager(CEO):
def managerMethod(self):
print ("I am the Manager")
class Employee1(Manager):
def employee1Method(self):
print ("I am Employee one")
class Employee2(Manager, CEO):
def employee2Method(self):
print ("I am Employee two")
# creating instances
emp = Employee2()
# method calls
[Link]()
[Link]()
emp.employee2Method()
On running the above program, it will give the below result −
I am the Manager
I am the CEO
I am Employee two
The super() function
In Python, super() function allows you to access methods and attributes of the parent class
from within a child class.
Example
In the following example, we create a parent class and access its constructor from a subclass
using the super() function.
Open Compiler
# parent class
class ParentDemo:
def __init__(self, msg):
[Link] = msg
def showMessage(self):
print([Link])
# child class
class ChildDemo(ParentDemo):
def __init__(self, msg):
# use of super function
super().__init__(msg)
# creating instance
obj = ChildDemo("Welcome to Tutorialspoint!!")
[Link]()