Python · Module 07: Object-Oriented Programming (OOP)Tutorial 20 of 30

7.2 Encapsulation (@property), Inheritance, super() & Polymorphism

Master the pillars of OOP the Pythonic way: protect data cleanly with @property, reuse parent logic with inheritance & super(), and write flexible code with polymorphism and Duck Typing.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Encapsulation: Protecting Data with _ and @property

In Java, you write noisy getBalance() / setBalance() methods. In Python:

  • _balance (single underscore) = "Internal — please don't touch directly."
  • @property lets you read acc.balance like a normal attribute while still running validation whenever someone assigns acc.balance = ...!
PYTHON
class Wallet:
    def __init__(self, balance=0):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Balance cannot be negative!")
        self._balance = value

w = Wallet(100)
w.balance = 250       # ✓ Runs setter validation automatically!
print(w.balance)      # 250

2. Inheritance (super()) & Polymorphism

Inheritance lets a child class reuse a parent's code and customize only what's different. Polymorphism ("many forms") means different classes share the same method name (pay(amount)), so your checkout code doesn't care whether the user picked UPI or Card!

Visual: Inheritance (`super()`) & Polymorphism (Same Method Name, Custom Behavior)
Parent: PaymentMethodpay(amount) · receipt()Child: UpiPayment(PaymentMethod)Overrides pay() → sends via VPAChild: CardPayment(PaymentMethod)Overrides pay() → charges Visa/MC
PYTHON
class PaymentMethod:
    def __init__(self, owner):
        self.owner = owner

    def pay(self, amount):
        raise NotImplementedError("Subclasses must implement pay()")

class UpiPayment(PaymentMethod):
    def __init__(self, owner, vpa):
        super().__init__(owner)     # Reuse parent's __init__!
        self.vpa = vpa

    def pay(self, amount):
        return f"Paid ₹{amount} via UPI ({self.vpa})"

class CardPayment(PaymentMethod):
    def pay(self, amount):
        return f"Charged ₹{amount} to {self.owner}'s Card"

# Polymorphism in action — one clean loop handles ANY payment method!
methods = [UpiPayment("Aarav", "aarav@upi"), CardPayment("Riya")]
for m in methods:
    print(m.pay(500))

3. Duck Typing: Python's Secret Superpower

"If it walks like a duck and quacks like a duck, Python treats it as a duck!"

In Python, two classes don't even need a shared parent class to work polymorphically — as long as both implement .pay(amount), your checkout function works seamlessly!

Design Rule: Prefer Composition ("A Car has-an Engine") over deep Inheritance trees ("A Dog is-an Animal"). Keep inheritance 1–2 levels shallow.


4. Interactive Trace: Polymorphic Checkout Loop

Tracing Polymorphic pay() Across Subclasses
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→methods = [UpiPayment("Aarav", "a@upi"), CardPayment("Riya")]
2for m in methods:
3 receipt = m.pay(500)
4 print(receipt)
Variables in Memory
methods[UpiPayment, CardPayment]list
Console Output
(nothing printed yet)
What just happened: Creates a list holding two different PaymentMethod subclasses.

Quick Quiz: Module 7.2 — Encapsulation, Inheritance & Polymorphism

Q1.What does `super().__init__(owner)` do inside a child class?
Q2.What is the Pythonic way to add validation when reading/writing an attribute like `user.age`?
Q3.What does 'Duck Typing' mean in Python?

Keep Exploring: Related Lessons & Tools

All Courses →