• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Inheritance in Python and its types

  • December 17, 2022
  • CODE OF GEEKS
  • 2


Next Tutorial >> super keyword in Python

Inheritance is one of the most important concept in object-oriented programming. Inheritance allows us to reuse the properties of existing class into the other class.

Main idea behind the Inheritance is that a child class acquires all the properties of its parent class and can access all the data members and functions of the parent class.

In programming terminology, we call parent class as base class and child class as derived class.

Inheritance in Python

Achieving Inheritance in Python

We can implement Inheritance in following way :

class Derived(Base)

Above code means, class Derived is inheriting all the properties (data members, methods) of its parent class Base.

A class can also inherit properties from multiple classes.

class Derived(Base1, Base2, Base3)

Let’s consider one example to showcasing Inheritance,

class Base:
    def display(self):
        print('Inside Base class')

class Derived(Base): # Derived class inheriting Base class 
    def get_method_from_base_class(self):
        self.display() # calling display method from Base class

d = Derived() # creating object for Derived class
d.get_method_from_base_class() # calling method of Derived class 

O/P

Inside Base class



Please note that, if we try to access the member without inheriting the class, then it will result in

AttributeError: ‘Derived’ object has no attribute ‘display’

Constructors in Inheritance

As of now, we know that when a derived class inherits the base class, then, all the variables and methods of base class become accessible from derived class.

But, what about constructors ?

Let’s see whether that can be inherited or not,

class Programming: # base class
    def __init__(self):
        self.lang = 'Python'
        
class Python(Programming):
    def display(self):
        print('Language of Mars: ', self.lang) # trying to access self.lang from Programming class 

p = Python()
p.display()

O/P

Language of Mars: Python

Hence, from the above code, it is clear that the constructor of the base class is accessible from the sub-class(derived class).

Please note that, writing a constructor in the derived class (subclass) will override the constructor of base class(parent class). In this case, parent class constructor will not be available.

Let’s try to alter the above code itself

class Programming: # base class
    def __init__(self):
        self.lang = 'Python'
        
class Python(Programming):
    def __init__(self): # defining constructor for this subclass
        self.no_lang = 'Python'
    def display(self):
        print('Language of Mars: ', self.lang) # trying to access self.lang from Programming class 

p = Python()
p.display()

O/P

AttributeError: ‘Python’ object has no attribute ‘lang’

Solution to above problem is to make use of super keyword in Python.



Types of Inheritance in Python

1. Single Inheritance

Single Inheritance is the type of Inheritance that comes into picture when a sub class inherits the properties of its parent class.

Single Inheritance
Single Inheritance

In Single Inheritance, there can be only one base class, but there can be ‘n‘ number of subclasses derived from it.

Syntax

class A:
  # statements
class B(A):
  # statements
class C(A):
  # statements
...

Code below is the example of Single Inheritance.

class Backend:
    def __init__(self):
        self.statusCode = 200
        
class Api(Backend):
    def return_body(self):
        if self.statusCode == 200:
            return {'statusCode': 200, 'body': "OK"};
        else:
            return {'statusCode': 500, 'body': "NOT OK"};

api = Api()
response = api.return_body()
print(response)

Here, we have defined two classes :

Backend: Parent class
Api: Child class

We are trying to access ‘self.statusCode’ variable from parent class into our child class.

This is the clear cut example of Single Inheritance.



2. Multilevel Inheritance

Just like other object oriented languages, Multilevel Inheritance is valid in Python as well.

In Multilevel Inheritance, there is a hierarchy where lower level class inherits the upper level class. For example,
class D inherits class C. (C is the parent of D)
class C inherits class B. (B is the parent of C)
class B inherits class A. (A is the parent of B)

Multilevel Inheritance in Python
Multilevel Inheritance in Python

Syntax

class A:
  # statements
class B(A):
  # statements
class C(B):
  # statements
class D(C):
  # statements
...

Code below is the example of Multilevel Inheritance.

class Lovers: 
    def post(self):
        print('He loves she')
class Haters(Lovers): 
     def send(self):
        self.post() # from Lovers
        print('He hates she')
class Introverts(Haters):
    def write(self):
        self.send() # from Haters
        print('He is a programmer')

l = Introverts()
l.write()

O/P

He loves she
He hates she
He is a programmer

3. Multiple Inheritance

Python supports Multiple Inheritance.

In Multiple Inheritance, a derived class can have more than one base class.

In other words, there will be more than one parent class and there may be one or more child classes.

Multiple Inheritance in Python
Multiple Inheritance in Python

Syntax

class A:
  # statements
class B:
  # statements
class C:
  # statements
class D(A, B, C):
  # statements
...

Code below is the example of Multiple Inheritance.

Problem with Multiple Inheritance: Check here



class Father:
    def father(self):
        print('calling Father')
        
class Mother:
    def mother(self):
        print('calling Mother')
        
class Son(Father, Mother):
    def son(self):
        self.father() # from Father
        self.mother() # from Mother
        print('calling son')

s = Son()
s.son()

O/P

calling Father
calling Mother
calling son



Well, that’s all about Inheritance in Python.

Tags: about inheritance in pythonall types of inheritance in pythonbase class inheritance in pythonclass and instance attributes in pythonclass inheritance in pythonclasses and objects in python exampleclasses and objects in python example programsconstructor in inheritance in pythondefine classes and objects in pythonexample of inheritance in pythonexplain inheritance in pythonexplain inheritance in python with an examplehierarchical inheritance in pythonillustrate class inheritance in python with an exampleinheritance concept in pythoninheritance definition in pythoninheritance in pythoninheritance in python 3inheritance in python and its typesinheritance in python exampleinheritance in python example programinheritance in python geeksforgeeksinheritance in python override a methodinheritance in python with an exampleinheritance in python with exampleinheritance program in pythoninheritance python advantagesinheritance types in pythonmultilevel inheritance in pythonmultilevel inheritance in python examplemultilevel inheritance pythonmultiple inheritance example in pythonmultiple inheritance in pythonmultiple inheritance in python examplepython class inheritancepython class inheritance examplepython class multiple inheritancepython classes and inheritancepython classes and objects examplespython classes objectspython derived classpython extend classpython inheritance examplepython multiple inheritancepython oop inheritancepython supports multiple inheritancepython3 class inheritancesingle inheritance in pythonsubclass pythonsyntax of inheritance in pythontypes inheritance in pythontypes of inheritance in pythonuse of inheritance in pythonwhat are classes and objects in pythonwhat is class and object in python with example
  • Previous InfyTQ Previous Year Python Questions
  • Next Class variables and Class methods in Python Class

2 comments on “Inheritance in Python and its types”

  1. kralb says:
    January 5, 2023 at 8:11 am

    Nice article, but to complete this basic picture you really should have include example with super() inheritance of constructor 🙂

    Reply
    1. CODE OF GEEKS says:
      January 5, 2023 at 1:44 pm

      Thanks for your appreciation. We have a dedicated article for super() as well: http://codeofgeeks.com/super-statement-in-python-with-examples/#problem-with-multiple-inheritance

      Reply

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.