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.
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."@propertylets you readacc.balancelike a normal attribute while still running validation whenever someone assignsacc.balance = ...!
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!
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
Quick Quiz: Module 7.2 — Encapsulation, Inheritance & Polymorphism
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.