- Object-Oriented Programming (OOP) in Python
-
Overview
- Introduction to OOP in Python
- Classes and Objects
- Constructors (__init__) and Destructors
- Inheritance (Single, Multiple, Multilevel)
- Polymorphism and Method Overriding
- Encapsulation and Data Hiding
- Abstract Classes and Interfaces
- Static and Class Methods
- Magic/Dunder Methods (__str__, __repr__)
- Metaclasses in Python
- Method Resolution Order (MRO) in Python
Inheritance (Single, Multiple, Multilevel)
Add to BookmarkWhat is Inheritance?
Inheritance is a core concept in Object-Oriented Programming (OOP) that allows a class (child class) to reuse the attributes and methods of another class (parent class). This improves code efficiency and maintains a hierarchical relationship between different classes.
Imagine you are building a website called "Dynamic Duniya", which offers different user roles like Admin, Editor, and Viewer. Instead of defining common features separately for each role, you can create a base User class and allow specific roles to inherit from it.
Types of Inheritance in Python
Python supports several types of inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
1. Single Inheritance
In single inheritance, a child class inherits from a single parent class.
Example: "Dynamic Duniya" User Roles
class User: # Parent class
def __init__(self, name):
self.name = name
def show_details(self):
print(f"User: {self.name}")
class Admin(User): # Child class inheriting from User
def access_dashboard(self):
print(f"{self.name} has admin access to Dynamic Duniya!")
# Creating an object of the Admin class
admin1 = Admin("Rajesh Kumar")
admin1.show_details() # Inherited from User class
admin1.access_dashboard() # Defined in Admin class
Output:
User: Rajesh Kumar
Rajesh Kumar has admin access to Dynamic Duniya!
The Admin
class inherits the show_details()
method from the User
class.
2. Multiple Inheritance
In multiple inheritance, a child class inherits from more than one parent class.
Example: "Dynamic Duniya" Content Moderation Team
class Editor:
def edit_content(self):
print("Editing content on Dynamic Duniya...")
class Moderator:
def moderate_comments(self):
print("Moderating comments on articles...")
class ContentManager(Editor, Moderator): # Inheriting from both Editor and Moderator
def manage_platform(self):
print("Managing all content on Dynamic Duniya.")
# Creating an object of ContentManager
content_manager = ContentManager()
content_manager.edit_content() # Inherited from Editor
content_manager.moderate_comments() # Inherited from Moderator
content_manager.manage_platform() # Defined in ContentManager
Output:
Editing content on Dynamic Duniya...
Moderating comments on articles...
Managing all content on Dynamic Duniya.
The ContentManager
class inherits from both Editor
and Moderator
, gaining access to their methods.
3. Multilevel Inheritance
In multilevel inheritance, a child class inherits from another child class, forming a chain.
Example: E-commerce System on "Dynamic Duniya"
class Person:
def __init__(self, name):
self.name = name
def show_name(self):
print(f"Name: {self.name}")
class Customer(Person): # Customer inherits from Person
def place_order(self):
print(f"{self.name} placed an order on Dynamic Duniya.")
class PrimeCustomer(Customer): # PrimeCustomer inherits from Customer
def get_prime_discount(self):
print(f"{self.name} received a special Prime discount!")
# Creating an object of PrimeCustomer
customer1 = PrimeCustomer("Neha Sharma")
customer1.show_name() # Inherited from Person
customer1.place_order() # Inherited from Customer
customer1.get_prime_discount() # Defined in PrimeCustomer
Output:
Name: Neha Sharma
Neha Sharma placed an order on Dynamic Duniya.
Neha Sharma received a special Prime discount!
The PrimeCustomer
class inherits from Customer
, which in turn inherits from Person
, forming a chain.
Method Overriding in Inheritance
A child class can override a method from the parent class to modify its behavior.
Example: Custom Greetings for Users
class User:
def greet(self):
print("Welcome to Dynamic Duniya!")
class VIPUser(User):
def greet(self): # Overriding the parent method
print("Welcome, valued VIP user of Dynamic Duniya!")
# Creating an object of VIPUser
vip1 = VIPUser()
vip1.greet() # Output: Welcome, valued VIP user of Dynamic Duniya!
Output:
Welcome, valued VIP user of Dynamic Duniya!
The VIPUser
class overrides the greet()
method of the User
class to provide a personalized greeting.
Summary
Single Inheritance: One parent, one child class.
Multiple Inheritance: A child class inherits from multiple parent classes.
Multilevel Inheritance: A child inherits from another child class.
Method Overriding: The child class redefines a method of the parent class.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- What is YII? and How to Install it?
- Top 10 Blogs of Digital Marketing you Must Follow
- Why to learn Digital Marketing?
- Exploratory Data Analysis On Iris Dataset
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Datasets for Natural Language Processing
- 15 Amazing Keyword Research Tools You Should Explore
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Generative AI - The Future of Artificial Intelligence
- Types of Numbers in Python
- Convert RBG Image to Gray Scale Image Using CV2
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Deep Learning (DL): The Core of Modern AI
- 5 Ways Use Jupyter Notebook Online Free of Cost
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset