Python Inheritance Tutorial- Method Overloading & Method Overriding
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In this Python tutorial, we talk about Python inheritance and types of inheritance in python with their syntax.
Moreover, we will study Python super function, Python method overriding and Python method overloading.
So, let’s start the Python Inheritance Tutorial.
What is Inheritance in Python?
It is a universal fact that every student is a person. This is in hindsight of non-human students if any. To depict this relationship, we take an illustration.
The relationship from person to a student is termed ‘Specialization’. Conversely, every student is a person, this is called Generalization.
In this representation, we use an arrow towards the base class as a UML (Unified Modeling Language) convention.
Here, Person can be called any of the following:
- Super Class
- Parent Class
- Base Class
Likewise, Student here is:
- Sub Class
- Child Class
- Derived Class
Python Inheritance Syntax
To make a class inherit from another, we apply the name of the base class in parentheses to the derived class’ definition.
>>> class Person: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class Student(Person): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> issubclass(Student,Person)
Output
Here, class Student inherits from class Person. Here, since we only want to focus on the python syntax, we use the ‘pass’ statement in the bodies of the classes.
Also, we use the function issubclass() to confirm that student is a subclass of person.
Types of Inheritance in Python
There are five types of inheritance in python, we observe.
1. Single Inheritance in Python
A single Python inheritance is when a single class inherits from a class.
>>> x=0 >>> class fruit:                def __init__(self):                                global x                                x+=1                                print("I'm a fruit")              >>> class citrus(fruit):                def __init__(self):                                super().__init__()                                global x                                x+=2                                print("I'm citrus")               >>> x
>>> lime=citrus()
Output
I’m citrus
>>> x
Output
3
2. Python Multiple Inheritance
Multiple Python inheritance are when a class inherits from multiple base classes.
>>> class Color: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class Fruit: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class Orange(Color,Fruit): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> issubclass(Orange,Color) and issubclass(Orange,Fruit)
Output
True
3. Multilevel Inheritance in Python
When one class inherits from another, which in turn inherits from another, it is multilevel python inheritance.
>>> class A: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â x=1 Â Â Â Â Â >>> class B(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class C(B): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> cobj=C() >>> cobj.x
Output
1
4. Hierarchical Inheritance in Python
When more than one class inherits from a class, it is hierarchical Python inheritance.
>>> class A: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class B(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class C(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> issubclass(B,A) and issubclass(C,A)
Output
True
5. Hybrid Inheritance in Python
Hybrid Python inheritance is a combination of any two kinds of inheritance.
>>> class A: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â x=1 Â Â Â >>> class B(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class C(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> class D(B,C): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pass >>> dobj=D() >>> dobj.x
Output
1
Python Inheritance Super Function – Super()
With inheritance, the super() function in python actually comes in quite handy. It allows us to call a method from the parent class.
Let’s define a new class for this.
>>> class Vehicle: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â def start(self): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â print("Starting engine") Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â def stop(self): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â print("Stopping engine")Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â >>> class TwoWheeler(Vehicle): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â def say(self): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â super().start() Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â print("I have two wheels") Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â super().stop() Â Â Â Â Â Â Â Â Â Â Â Â Â Â >>> Pulsar=TwoWheeler() >>> Pulsar.say()
Output
I have two wheels
Stopping engine
Python Override Method
A subclass may change the functionality of a Python method in the superclass. It does so by redefining it.
This is termed python method overriding. Lets see this Python Method Overriding Example.
>>> class A: Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â def sayhi(self): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â print("I'm in A")Â Â Â Â Â Â Â Â Â Â Â Â Â Â >>> class B(A): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â def sayhi(self): Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â print("I'm in B")Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â >>> bobj=B() >>> bobj.sayhi()
Output
I’m in B
Python Method Overloading
Before we say anything, we’d like you to take a look at the following code:
>>> def add(a,b): return a+b >>> def add(a,b,c): return a+b+c >>> add(2,3)
Output
File “<pyshell#8>”, line 1, in <module>
add(2,3)
TypeError: add() missing 1 required positional argument: ‘c’
What looks like overloading methods, it is actually that Python keeps only the latest definition of a method you declare to it.
This code doesn’t make a call to the version of add() that takes in two arguments to add. So we find it safe to say Python doesn’t support method overloading.
However, we recently ran into a rather Pythonic way to make this happen. Check this out:
>>> def add(instanceOf,*args): if instanceOf=='int': result=0 if instanceOf=='str': result='' for i in args: result+=i return result
In this code, not only do we use the *args magic variable for variable arity, we also let the code deal with both integers and strings.
Watch it happen:
>>> add('int',3,4,5)
Output
12
>>> add('str','I ','speak ','Python')
Output
‘I speak Python’
You say what if I do this?:
>>> def add(a,b,c=0):
Output
return a+b+c
>>> add(2,3)
Output
5
To that, we’ll say this isn’t method overloading, this is simply used of default arguments.
Python Interview Questions on Inheritance
- How does inheritance work in Python?
- What are the types of inheritance in Python?
- Does Python support multiple inheritance?
- What is Python inheritance? Explain with example.
- Is hierarchical inheritance possible in Python?
Conclusion
Of all things good, Python inheritance saves us time, effort, and memory.
In this tutorial, we looked at Python inheritance syntax, inheritance types, Python method overloading, method overriding in python and python super functions.
Tell us in a comment box, if something is missing.
Did you like this article? If Yes, please give DataFlair 5 Stars on Google
Update your programs for Python 3. Lot of which are not running, so not able to understand your examples clearly.
Hi Varun,
I feel you are just copy and pasting the code. Please Intend the codes appropriately it will work.
Thanks,
Veeresh
“Hi, Varun
Any piece of code on this blog “Python Inheritance” should work fine with Python 3.x. Have you checked your indentation once?
Since Python does not mandate use of curly braces, indentation is a must.
Read up on Python Syntax – you will need to indent the statements under one block to the same number of tabs and/or spaces.
You could also check if you are indeed working on Python 3.x.”
Method overloading is not supported in python. In this example, you are calling the same function/method with some default values. If we have more than on method with the same name, only the latest one is considered.
Hi Py_dev,
Thanks for connecting DataFlair.
Before we say anything, we’d like you to take a look at the following code:
>>> def add(a,b):
return a+b
>>> def add(a,b,c):
return a+b+c
>>> add(2,3)
Traceback (most recent call last):
File “”””, line 1, in
add(2,3)
TypeError: add() missing 1 required positional argument: ‘c’
What looks like overloading methods, it is actually that Python keeps only the latest definition of a method you declare to it. This code doesn’t make a call to the version of add() that takes in two arguments to add. So we find it safe to say Python doesn’t support method overloading. However, we recently ran into a rather Pythonic way to make this happen. Check this out:
>>> def add(instanceOf,*args):
if instanceOf==’int’:
result=0
if instanceOf==’str’:
result=”
for i in args:
result+=i
return result
In this code, not only do we use the *args magic variable for variable arity, we also let the code deal with both integers and strings. Watch it happen:
>>> add(‘int’,3,4,5)
12
>>> add(‘str’,’I ‘,’speak ‘,’Python’)
‘I speak Python’
You say what if I do this?:
>>> def add(a,b,c=0):
return a+b+c
>>> add(2,3)
5
To that, we’ll say this isn’t method overloading, this is simply used of default arguments.
can we restrict a base class to not to inherit by the child class?
Greetings, Vinod
Thanks for commenting on “Python Inheritance”. Final classes are not Pythonic. What we mean to say is- this is not something Python intends to make possible and there is no keyword for this.
The flag Py_TPFLAGS_BASETYPE is something we can set via the C API to decide which classes we can subclass.
When this bit is clear, it means it isn’t possible to subtype this class. This is like final classes in Java.
However, it is also possible to emulate this behavior using nothing but Python:
>>> class Final(type):
def __new__(cls, name, bases, classdict):
for b in bases:
if isinstance(b, Final):
raise TypeError(“type ‘{0}’ is not an acceptable base type”.format(b.__name__))
return type.__new__(cls, name, bases, dict(classdict))
>>> class C(metaclass=Final): pass
>>> class D(C): pass
Traceback (most recent call last):
File “”, line 1, in
class D(C): pass
File “”, line 5, in __new__
raise TypeError(“type ‘{0}’ is not an acceptable base type”.format(b.__name__))
TypeError: type ‘C’ is not an acceptable base type
Hope you understood.
Regards,
DataFlair
The ‘return result’ statement in the last program (args one) should be written without indentation. Otherwise the function ‘add’ will return in the first iteration itself.
Thank you for noticing, people like you help improve the experience for other users. We have made necessary changes in this Python Inheritance. Please refer our other Python tutorials.
Regards,
DataFlair
Hello,
Am’I missing something here?? getting this following error:
UnboundLocalError: local variable ‘result’ referenced before assignment
Hi Amol,
Thanks for connecting DataFlair through this “Python Inheritance” Tutorial. Here, the error tells you that you have tried to access ‘result’ without first assigning it.
You could have put ‘result’ instead of ‘result=0’ or any of the assignment statements under the if-conditions.
Hope, it helps you!
This tutorial is awesome. Well structured. Easy to learn and understand. Thank you. Great work. If you don’t mind, consider this one thing that example codes should have indentation so that beginner shouldn’t struggle to read the code. Python IDLE is okay upto variables. After that, example codes will be long. it is better code should have indentation.
In Case of Multiple Inheritance, how to inherit both the __init__methods of parent classes (say: A and B are both parent class) into a child class (say : c as child class inheriting from both A and B), using super().__init__() method.
You can call A’s init method using “A.__init__(self)” abd B’s init method using “B.__init__(self)” inside C’s init method.