Polymorphism, Encapsulation & Inner Classes
Polymorphism means different classes can respond to the same method name differently.
Python Polymorphism
Polymorphism means different classes can respond to the same method name differently.
Duck typing: if it quacks like a duck, use it — Python cares about behavior, not exact type.
Real-life example: A 'Play' button on TV, phone, and speaker — same action, different devices inside.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
for animal in [Cat(), Dog()]:
print(animal.speak())Python Encapsulation
Encapsulation hides internal details. Convention: prefix with _ for 'private' (still accessible but a hint).
Use methods to validate changes instead of editing attributes from everywhere.
Real-life example: Encapsulation is an ATM — you press buttons, not open the vault yourself.
class Account:
def __init__(self):
self._balance = 0
def deposit(self, amount):
if amount > 0:
self._balance += amount
def get_balance(self):
return self._balancePython Inner Classes
A class defined inside another class can group related helpers tightly.
Use when the inner class only makes sense with the outer one — not for every project.
Real-life example: Inner class is a drawer inside one desk — not a separate room in the building.
class University:
class Student:
def __init__(self, name):
self.name = name
def enroll(self, name):
return self.Student(name)
u = University()
s = u.enroll("Riya")
print(s.name)