Movatterモバイル変換


[0]ホーム

URL:


Open In App

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). In this article, we'll explore inheritance in Python.

Example:Here, we create a parent class Animal that has a method info(). Then we create a child classes Dog that inherit from Animal and add their own behavior.

Python
classAnimal:def__init__(self,name):self.name=namedefinfo(self):print("Animal name:",self.name)classDog(Animal):defsound(self):print(self.name,"barks")d=Dog("Buddy")d.info()# Inherited methodd.sound()

Output
Animal name: BuddyBuddy barks

Explanation:

  • class Animal: Defines the parent class.
  • info():Prints the name of the animal.
  • class Dog(Animal): Defines Dog as a child of Animal class.
  • d.info(): Calls parent method info() andd.sound(): Calls child method.
animal_class
Inheritance in Python

Why do we need Inheritance

  • Promotes code reusability by sharing attributes and methods across classes.
  • Models real-world hierarchies like Animal -> Dog or Person -> Employee.
  • Simplifies maintenance through centralized updates in parent classes.
  • Enables method overriding for customized subclass behavior.
  • Supports scalable, extensible design using polymorphism.

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:Here, Dog uses super() to call Animal’s constructor

Python
# Parent Class: AnimalclassAnimal:def__init__(self,name):self.name=namedefinfo(self):print("Animal name:",self.name)# Child Class: DogclassDog(Animal):def__init__(self,name,breed):super().__init__(name)# Call parent constructorself.breed=breeddefdetails(self):print(self.name,"is a",self.breed)d=Dog("Buddy","Golden Retriever")d.info()# Parent methodd.details()# Child method

Output
Animal name: BuddyBuddy is a Golden Retriever

Explanation:

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

Types of Python Inheritance

Inheritance be used in different ways depending on how many parent and child classes are involved. They help model real-world relationships more effectively and allow flexibility in code reuse.

Python supports several types of inheritance, let's explore it one by one:

1. Single Inheritance

In single inheritance, a child class inherits from just one parent class.

Example:This example shows a child class Employee inheriting a property from the parent class Person.

Python
classPerson:def__init__(self,name):self.name=nameclassEmployee(Person):# Employee inherits from Persondefshow_role(self):print(self.name,"is an employee")emp=Employee("Sarah")print("Name:",emp.name)emp.show_role()

Output
Name: SarahSarah is an employee

Explanation: Here Employee inherits name from Person, it also defines its own method show_role().

2. Multiple Inheritance

In multiple inheritance, a child class can inherit from more than one parent class.

Example:This example demonstrates Employee inheriting properties from two parent classes: Person and Job.

Python
classPerson:def__init__(self,name):self.name=nameclassJob:def__init__(self,salary):self.salary=salaryclassEmployee(Person,Job):# Inherits from both Person and Jobdef__init__(self,name,salary):Person.__init__(self,name)Job.__init__(self,salary)defdetails(self):print(self.name,"earns",self.salary)emp=Employee("Jennifer",50000)emp.details()

Output
Jennifer earns 50000

Explanation: Here Employee gets attributes from both Person and Job and It can access both name and salary.

3. Multilevel Inheritance

In multilevel inheritance, a class is derived from another derived class (like a chain).

Example:This example shows Manager inheriting from Employee, which in turn inherits from Person.

Python
classPerson:def__init__(self,name):self.name=nameclassEmployee(Person):defshow_role(self):print(self.name,"is an employee")classManager(Employee):# Manager inherits from Employeedefdepartment(self,dept):print(self.name,"manages",dept,"department")mgr=Manager("Joy")mgr.show_role()mgr.department("HR")

Output
Joy is an employeeJoy manages HR department

Explanation: Here Manager inherits from Employee and Employee inherits from Person. So Manager can use methods from both parent and grandparent.

4. Hierarchical Inheritance

In hierarchical inheritance, multiple child classes inherit from the same parent class.

Example:This example demonstrates two child classes (Employee and Intern) inheriting from a single parent class Person.

Python
classPerson:def__init__(self,name):self.name=nameclassEmployee(Person):defrole(self):print(self.name,"works as an employee")classIntern(Person):defrole(self):print(self.name,"is an intern")emp=Employee("David")emp.role()intern=Intern("Eva")intern.role()

Output
David works as an employeeEva is an intern

Explanation: Both Employee and Intern inherit from Person. They share the parent’s property (name) but implement their own methods.

5. Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

Example:This example demonstrates TeamLead inheriting from both Employee (which inherits Person) and Project, combining multiple inheritance types.

Python
classPerson:def__init__(self,name):self.name=nameclassEmployee(Person):defrole(self):print(self.name,"is an employee")classProject:def__init__(self,project_name):self.project_name=project_nameclassTeamLead(Employee,Project):# Hybrid Inheritancedef__init__(self,name,project_name):Employee.__init__(self,name)Project.__init__(self,project_name)defdetails(self):print(self.name,"leads project:",self.project_name)lead=TeamLead("Sophia","AI Development")lead.role()lead.details()

Output
Sophia is an employeeSophia leads project: AI Development

Explanation: Here TeamLead inherits from Employee (which already inherits Person) and also from Project. This combines single, multilevel and multiple inheritance -> hybrid.

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


Inheritance in Python
Visit Courseexplore course icon
Improve
Improve
Article Tags :

Explore

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

[8]ページ先頭

©2009-2025 Movatter.jp