Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Method Overriding in Python
Next article icon

Inheritance in Python

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this article, we’ll explore inheritance in Python.

Basic Example of Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Python
# Parent class class Animal:     def __init__(self, name):         self.name = name  # Initialize the name attribute      def speak(self):         pass  # Placeholder method to be overridden by child classes  # Child class inheriting from Animal class Dog(Animal):     def speak(self):         return f"{self.name} barks!"  # Override the speak method  # Creating an instance of Dog dog = Dog("Buddy") print(dog.speak())   

Output
Buddy barks! 

Explanation:

  • Animal is the parent class with an __init__ method and a speak method.
  • Dog is the child class that inherits from Animal.
  • The speak method is overridden in the Dog class to provide specific behavior.

Let’s understand inheritance in detail:

Table of Content

  • Syntax for Inheritance
  • Explanation of Python Inheritance Syntax
  • Creating a Parent Class
  • Creating a Child Class
  • __init__() Function
  • super() Function
  • Add Properties
  • Types of Python Inheritance

Syntax for Inheritance

class ParentClass:

# Parent class code here
pass

class ChildClass(ParentClass):

# Child class code here
pass

Explanation of Python Inheritance Syntax

  1. Parent Class:
    • This is the base class from which other classes inherit.
    • It contains attributes and methods that the child class can reuse.
  2. Child Class:
    • This is the derived class that inherits from the parent class.
    • The syntax for inheritance is class ChildClass(ParentClass).
    • The child class automatically gets all attributes and methods of the parent class unless overridden.

Creating a Parent Class

In object-oriented programming, a parent class (also known as a base class) defines common attributes and methods that can be inherited by other classes. These attributes and methods serve as the foundation for the child classes. By using inheritance, child classes can access and extend the functionality provided by the parent class.

Here’s an example where Person is the parent class:

Python
# A Python program to demonstrate inheritance class Person(object):      # Constructor   def __init__(self, name, id):     self.name = name     self.id = id    # To check if this person is an employee   def Display(self):     print(self.name, self.id)   # Driver code emp = Person("Satyam", 102) # An Object of Person emp.Display() 

Output
Satyam 102 

Explanation:

  • The Person class has two attributes: name and id. These are set when an object of the class is created.
  • The display method prints the name and id of the person.

Creating a Child Class

A child class (also known as a subclass) is a class that inherits properties and methods from its parent class. The child class can also introduce additional attributes and methods, or even override the ones inherited from the parent.

In this case, Emp is the child class that inherits from the Person class:

Python
class Emp(Person):      def Print(self):     print("Emp class called")      Emp_details = Emp("Mayank", 103)  # calling parent class function Emp_details.Display()  # Calling child class function Emp_details.Print() 

Explanation:

  • Emp class inherits the name and id attributes and the display method from the Person class.
  • __init__ method in Emp calls super().__init__(name, id) to invoke the constructor of the Person class and initialize the inherited attributes.
  • Emp introduces an additional attribute, role, and also overrides the display method to print the role in addition to the name and id.

__init__() Function

__init__() function is a constructor method in Python. It initializes the object’s state when the object is created. If the child class does not define its own __init__() method, it will automatically inherit the one from the parent class.

In the example above, the __init__() method in the Employee class ensures that both inherited and new attributes are properly initialized.

Python
# Parent Class: Person class Person:     def __init__(self, name, idnumber):         self.name = name         self.idnumber = idnumber  # Child Class: Employee class Employee(Person):     def __init__(self, name, idnumber, salary, post):         super().__init__(name, idnumber)  # Calls Person's __init__()         self.salary = salary         self.post = post 

Explanation:

  • __init__() method in Person initializes name and idnumber.
  • __init__() method in Employee calls super().__init__(name, idnumber) to initialize the name and idnumber inherited from the Person class and adds salary and post.

super() Function

super() function is used to call the parent class’s methods. In particular, it is commonly used in the child class’s __init__() method to initialize inherited attributes. This way, the child class can leverage the functionality of the parent class.

Example:

Python
# Parent Class: Person class Person:     def __init__(self, name, idnumber):         self.name = name         self.idnumber = idnumber      def display(self):         print(self.name)         print(self.idnumber)  # Child Class: Employee class Employee(Person):     def __init__(self, name, idnumber, salary, post):         super().__init__(name, idnumber)  # Using super() to call Person's __init__()         self.salary = salary         self.post = post 

Explanation:

  • The super() function is used inside the __init__() method of Employee to call the constructor of Person and initialize the inherited attributes (name and idnumber).
  • This ensures that the parent class functionality is reused without needing to rewrite the code in the child class.

Add Properties

Once inheritance is established, both the parent and child classes can have their own properties. Properties are attributes that belong to a class and are used to store data.

Example:

Python
# Parent Class: Person class Person:     def __init__(self, name, idnumber):         self.name = name         self.idnumber = idnumber      def display(self):         print(self.name)         print(self.idnumber)  # Child Class: Employee class Employee(Person):     def __init__(self, name, idnumber, salary, post):         super().__init__(name, idnumber)         self.salary = salary         self.post = post 

Explanation:

  • Person class has properties name and idnumber.
  • Employee class adds properties salary and post.
  • The properties are initialized when an object is created, and they represent the specific data related to the Person and Employee.

Types of Python Inheritance

  1. Single Inheritance: A child class inherits from one parent class.
  2. Multiple Inheritance: A child class inherits from more than one parent class.
  3. Multilevel Inheritance: A class is derived from a class which is also derived from another class.
  4. Hierarchical Inheritance: Multiple classes inherit from a single parent class.
  5. Hybrid Inheritance: A combination of more than one type of inheritance.

Example:

Python
# 1. Single Inheritance class Person:     def __init__(self, name):         self.name = name  class Employee(Person):  # Employee inherits from Person     def __init__(self, name, salary):         super().__init__(name)         self.salary = salary  # 2. Multiple Inheritance class Job:     def __init__(self, salary):         self.salary = salary  class EmployeePersonJob(Employee, Job):  # Inherits from both Employee and Job     def __init__(self, name, salary):         Employee.__init__(self, name, salary)  # Initialize Employee         Job.__init__(self, salary)            # Initialize Job  # 3. Multilevel Inheritance class Manager(EmployeePersonJob):  # Inherits from EmployeePersonJob     def __init__(self, name, salary, department):         EmployeePersonJob.__init__(self, name, salary)  # Explicitly initialize EmployeePersonJob         self.department = department  # 4. Hierarchical Inheritance class AssistantManager(EmployeePersonJob):  # Inherits from EmployeePersonJob     def __init__(self, name, salary, team_size):         EmployeePersonJob.__init__(self, name, salary)  # Explicitly initialize EmployeePersonJob         self.team_size = team_size  # 5. Hybrid Inheritance (Multiple + Multilevel) class SeniorManager(Manager, AssistantManager):  # Inherits from both Manager and AssistantManager     def __init__(self, name, salary, department, team_size):         Manager.__init__(self, name, salary, department)        # Initialize Manager         AssistantManager.__init__(self, name, salary, team_size)  # Initialize AssistantManager  # Creating objects to show inheritance  # Single Inheritance emp = Employee("John", 40000) print(emp.name, emp.salary)  # Multiple Inheritance emp2 = EmployeePersonJob("Alice", 50000) print(emp2.name, emp2.salary)  # Multilevel Inheritance mgr = Manager("Bob", 60000, "HR") print(mgr.name, mgr.salary, mgr.department)  # Hierarchical Inheritance asst_mgr = AssistantManager("Charlie", 45000, 10) print(asst_mgr.name, asst_mgr.salary, asst_mgr.team_size)  # Hybrid Inheritance sen_mgr = SeniorManager("David", 70000, "Finance", 20) print(sen_mgr.name, sen_mgr.salary, sen_mgr.department, sen_mgr.team_size) 

Output
John 40000 Alice 50000 Bob 60000 HR Charlie 45000 10 David 70000 Finance 20 

Explanation:

  1. Single Inheritance: Employee inherits from Person, adding a salary attribute.
  2. Multiple Inheritance: EmployeePersonJob inherits from both Employee and Job, allowing access to both name and salary.
  3. Multilevel Inheritance: Manager inherits from EmployeePersonJob, which already includes Employee and Job.
  4. Hierarchical Inheritance: AssistantManager also inherits from EmployeePersonJob, demonstrating multiple child classes inheriting from the same parent.
  5. Hybrid Inheritance: SeniorManager inherits from both Manager (multilevel) and AssistantManager (hierarchical), combining two inheritance types.

For more details please read this article: Types of inheritance in Python



Next Article
Method Overriding in Python

S

ShivangiSrivastava1
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python OOPs Concepts
    Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
    11 min read
  • Python Classes and Objects
    A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
    6 min read
  • Python objects
    A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
    2 min read
  • Class and Object

    • self in Python class
      In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
      6 min read

    • Class and Instance Attributes in Python
      Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
      2 min read

    • Create a Python Subclass
      In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
      3 min read

    • Inner Class in Python
      Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
      5 min read

    • Python MetaClasses
      The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
      9 min read

    • Creating Instance Objects in Python
      In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
      3 min read

    • Dynamic Attributes in Python
      Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
      2 min read

    • Constructors in Python
      In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
      3 min read

    • Why Python Uses 'Self' as Default Argument
      In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Python’s object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
      3 min read

    Encapsulation and Access Modifiers

    • Encapsulation in Python
      In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
      6 min read

    • Access Modifiers in Python : Public, Private and Protected
      Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
      9 min read

    • Access Modifiers in Python : Public, Private and Protected
      Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
      9 min read

    • Private Variables in Python
      Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
      3 min read

    • Private Methods in Python
      Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
      6 min read

    • Protected variable in Python
      Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
      2 min read

    Inheritance

    • Inheritance in Python
      Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
      7 min read

    • Method Overriding in Python
      Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
      7 min read

    • Operator Overloading in Python
      Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
      9 min read

    • Python super()
      In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class. Syntax of super() in PythonSyntax: super() Return : R
      8 min read

    • Multiple Inheritance in Python
      Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
      5 min read

    • What Is Hybrid Inheritance In Python?
      Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
      3 min read

    • Multilevel Inheritance in Python
      Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
      3 min read

    • Multilevel Inheritance in Python
      Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
      3 min read

    Polymorphism

    • Polymorphism in Python
      Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
      7 min read

    • Python | Method Overloading
      Method Overloading: Two or more methods have the same name but different numbers of parameters or different types of parameters, or both. These methods are called overloaded methods and this is called method overloading. Like other languages (for example, method overloading in C++) do, python does n
      7 min read

    • Method Overriding in Python
      Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
      7 min read

    Abstraction

    • Data Abstraction in Python
      Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant details from the user and show the details that are relevant to the users. For example, the readers of geeksforgeeks only know that a writer can write an article on geeksforgeeks, and when it gets
      5 min read

    • Abstract Classes in Python
      In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide speci
      6 min read

    • Python-interface module
      In object-oriented languages like Python, the interface is a collection of method signatures that should be provided by the implementing class. Implementing an interface is a way of writing an organized code and achieve abstraction. The package zope.interface provides an implementation of "object in
      3 min read

    • Difference between abstract class and interface in Python
      In this article, we are going to see the difference between abstract classes and interface in Python, Below are the points that are discussed in this article: What is an abstract class in Python?What is an interface in Python?Difference between abstract class and interface in PythonWhat is an Abstra
      4 min read

    Special Methods and Testing

    • Dunder or magic methods in Python
      Python Magic methods are the methods starting and ending with double underscores '__'. They are defined by built-in classes in Python and commonly used for operator overloading.  They are also called Dunder methods, Dunder here means "Double Under (Underscores)". Python Magic MethodsBuilt in classes
      7 min read

    • __init__ in Python
      Prerequisites - Python Class and Objects, Self __init__ method in Python is used to initialize objects of a class. It is also called a constructor. It is like a default constructor in C++ and Java. Constructors are used to initialize the object’s state. The task of constructors is to initialize (ass
      5 min read

    • Object oriented testing in Python
      Prerequisite: Object-Oriented Testing Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes -
      5 min read

    Additional Resources

    • Object oriented testing in Python
      Prerequisite: Object-Oriented Testing Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes -
      5 min read

    • classmethod() in Python
      The classmethod() is an inbuilt function in Python, which returns a class method for a given function. This means that classmethod() is a built-in Python function that transforms a regular method into a class method. When a method is defined using the @classmethod decorator (which internally calls c
      8 min read

    • Decorators in Python
      In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
      10 min read

    • Destructors in Python
      Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
      7 min read

    • 8 Tips For Object-Oriented Programming in Python
      OOP or Object-Oriented Programming is a programming paradigm that organizes software design around data or objects and relies on the concept of classes and objects, rather than functions and logic. Object-oriented programming ensures code reusability and prevents Redundancy, and hence has become ver
      6 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences