Python Inheritance

Python tutorial · PySpark.in

What is Inheritance?

Inheritance allows a class (called the child class or derived class) to inherit the properties and methods of another class (called the parent class or base class). It helps in code reusability, extensibility, and maintaining a hierarchy between classes.

Why Use Inheritance?

Syntax

PLAINTEXT
1class ParentClass:
2 # parent class code
3class ChildClass(ParentClass):
4 # child class code
▶ Output will appear here.

Example: Single Inheritance

PYTHON
1# Parent class
2class Person:
3 def __init__(self, name):
4 self.name = name
5 def show(self):
6 print(f"Name: {self.name}")
7# Child class inheriting from Person
8class Student(Person):
9 def __init__(self, name, roll):
10 super().__init__(name) # calling parent constructor
11 self.roll = roll
12 def details(self):
13 print(f"Roll Number: {self.roll}")
14# Creating object of child class
15s1 = Student("Megha", 101)
16s1.show() # method from parent class
17s1.details() # method from child class
▶ Output will appear here.

Explanation

Example: Multilevel Inheritance

PYTHON
1class Grandparent:
2 def grand_info(self):
3 print("This is the Grandparent class.")
4class Parent(Grandparent):
5 def parent_info(self):
6 print("This is the Parent class.")
7class Child(Parent):
8 def child_info(self):
9 print("This is the Child class.")
10# Object of Child
11c = Child()
12c.grand_info()
13c.parent_info()
14c.child_info()
▶ Output will appear here.

Example: Multiple Inheritance

PYTHON
1class Teacher:
2 def teach(self):
3 print("Teaching students...")
4class Mentor:
5 def guide(self):
6 print("Guiding students...")
7# Child class inheriting from two parents
8class Professor(Teacher, Mentor):
9 def research(self):
10 print("Doing research...")
11p = Professor()
12p.teach()
13p.guide()
14p.research()
▶ Output will appear here.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges