- 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
- 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
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
Random Blogs
- Types of Numbers in Python
- Important Mistakes to Avoid While Advertising on Facebook
- Extract RGB Color From a Image Using CV2
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- The Ultimate Guide to Machine Learning (ML) for Beginners
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Quantum AI – The Future of AI Powered by Quantum Computing
- How to Start Your Career as a DevOps Engineer
- Best Platform to Learn Digital Marketing in Free
- Google’s Core Update in May 2020: What You Need to Know
- Datasets for analyze in Tableau
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Python Challenging Programming Exercises Part 3
- Python Challenging Programming Exercises Part 1
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