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?
- To reuse code from existing classes.
- To add or modify behavior without rewriting the parent class.
- To make programs more organized and modular.
Syntax
1class ParentClass:
2 # parent class code
3class ChildClass(ParentClass):
4 # child class code
▶ Output will appear here.
Example: Single Inheritance
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
- Person → Parent (Base) class
- Student → Child (Derived) class
- super().__init__(name) → calls the constructor of the parent class
- The child class inherits the show() method and defines its own details() method.
Example: Multilevel Inheritance
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
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
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges