- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Polymorphism Definition
Polymorphism means same function name, different behaviors, depending on class or input.
Two types in Python:
| Type | Meaning |
|---|---|
| Compile-time (Overloading) | Same function, different parameters (simulated in Python) |
| Runtime (Overriding) | Child class modifies parent method |
Method Overriding (Runtime Polymorphism)
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
for pet in [Dog(), Cat()]:
pet.speak()
Each object responds differently to the same speak() call.
Method Overloading (Simulated)
class Math:
def add(self, a, b, c=None):
if c:
return a + b + c
return a + b
m = Math()
print(m.add(1, 2))
print(m.add(1, 2, 3))
Python doesn’t support true overloading, so we use default parameters.
Polymorphism with Functions & Objects
class Car:
def move(self):
print("Car is driving")
class Plane:
def move(self):
print("Plane is flying")
def operate(vehicle):
vehicle.move()
operate(Car())
operate(Plane())
Same function → different behavior based on object type.
Polymorphism with Inheritance
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement this")
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
for s in [Square(4), Circle(5)]:
print(s.area())
Child classes provide unique logic for inherited structure.
Real-World Example (Combined)
class User:
def login(self):
print("Login from User")
class Admin(User):
def login(self):
print("Admin login with security check")
class Customer(User):
def login(self):
print("Customer login")
users = [Admin(), Customer(), User()]
for u in users:
u.login()
Explanation
Admin&Customeroverride thelogin()method.- Same method name → different behaviors based on object type.
Summary
| Feature | What It Does | Example |
|---|---|---|
| Inheritance | Reuse parent class features | class B(A) |
| Multiple Inheritance | Child from multiple parents | class C(A,B) |
| Polymorphism | Same method, different behavior | Overriding |
| Overriding | Modify parent method | Redefine in child |
| Overloading | Same name, different arguments | Default parameters |