R
Rishtaara
Python: Zero to Professional
Lesson 17 of 40Article16 min

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.

Same method, different classes
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.

Controlled access
class Account:
    def __init__(self):
        self._balance = 0

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def get_balance(self):
        return self._balance

Python 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.

Nested class
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)