- 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
Polymorphism and Method Overriding
What is Polymorphism?
Polymorphism in Python refers to the ability of different classes to share the same method name but exhibit different behaviors. This is a key feature of Object-Oriented Programming (OOP) that enhances code flexibility and reusability.
For example, in real life, a teacher and a student both have a speak() method, but they use it differently—a teacher explains concepts, while a student asks questions.
Python achieves polymorphism in two main ways:
- Method Overriding (in Inheritance)
- Method Overloading (not natively supported, but achievable)
1. Method Overriding in Python
Method overriding allows a child class to provide a different implementation of a method already defined in its parent class.
Example: Animals Making Sounds
Different animals make different sounds, but they all have a make_sound()
method.
class Animal:
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def make_sound(self): # Overriding parent method
print("Bark! Bark!")
class Cat(Animal):
def make_sound(self): # Overriding parent method
print("Meow! Meow!")
# Creating objects
dog = Dog()
cat = Cat()
dog.make_sound() # Output: Bark! Bark!
cat.make_sound() # Output: Meow! Meow!
Here, both Dog
and Cat
override the make_sound()
method of the Animal
class to provide their own implementation.
2. Method Overriding with super()
Sometimes, we may want to reuse the parent method while adding extra functionality. This is where super()
comes in.
Example: Employees in a Company
class Employee:
def work(self):
print("Completing assigned tasks.")
class Manager(Employee):
def work(self):
super().work() # Calling the parent method
print("Managing the team and projects.")
# Creating object
mgr = Manager()
mgr.work()
Output:
Completing assigned tasks.
Managing the team and projects.
The Manager
class first calls the work()
method of Employee
and then adds additional behavior.
3. Polymorphism in Functions and Methods
Polymorphism allows the same function to work with different objects.
Example: Vehicle Details
class Car:
def fuel_type(self):
return "Petrol or Diesel"
class ElectricCar:
def fuel_type(self):
return "Electric Battery"
# Function using Polymorphism
def vehicle_info(vehicle):
print(f"Fuel type: {vehicle.fuel_type()}")
# Calling function with different objects
vehicle_info(Car()) # Output: Fuel type: Petrol or Diesel
vehicle_info(ElectricCar()) # Output: Fuel type: Electric Battery
The vehicle_info()
function works with both Car and ElectricCar objects because they share the fuel_type()
method.
4. Duck Typing in Python
Python follows duck typing, which means an object’s behavior determines its usability rather than its type.
Example: Different Types of Payments
class CreditCard:
def make_payment(self):
print("Payment made using Credit Card.")
class UPI:
def make_payment(self):
print("Payment made using UPI.")
# Function that works with any payment method
def process_payment(payment_method):
payment_method.make_payment()
# Using different objects
process_payment(CreditCard()) # Output: Payment made using Credit Card.
process_payment(UPI()) # Output: Payment made using UPI.
Here, the process_payment()
function works with any object that has a make_payment()
method, regardless of its class.
5. Method Overloading (Achieved Using Default Arguments)
Python does not support method overloading natively, but we can achieve a similar effect using default parameters.
Example: Calculating Area
class Shape:
def area(self, length, breadth=None):
if breadth is None: # If only one parameter is given, calculate square area
return length * length
else: # If two parameters are given, calculate rectangle area
return length * breadth
shape = Shape()
print(shape.area(5)) # Square -> Output: 25
print(shape.area(5, 10)) # Rectangle -> Output: 50
Here, the area()
method works for both squares (one parameter) and rectangles (two parameters).
Summary
Method Overriding allows a child class to redefine a method from its parent class.
super() can be used to call the parent class’s method while extending it.
Polymorphism enables the same method name to work with different object types.
Duck Typing ensures an object is used based on its behavior, not its class.
Method Overloading is simulated using default arguments.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- SQL Joins Explained: A Complete Guide with Examples
- String Operations in Python
- Python Challenging Programming Exercises Part 2
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Robotics & AI – How AI is Powering Modern Robotics
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- How to Become a Good Data Scientist ?
- How to Start Your Career as a DevOps Engineer
- Python Challenging Programming Exercises Part 3
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- 15 Amazing Keyword Research Tools You Should Explore
- Datasets for Exploratory Data Analysis for Beginners
- The Ultimate Guide to Machine Learning (ML) for Beginners
Datasets for Machine Learning
- 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
- Bitcoin Heist Ransomware Address Dataset