Topic 6 of 64
OOP
Overview
Python supports full object-oriented programming with classes, inheritance, encapsulation, and polymorphism. OOP is critical for building maintainable large-scale applications and is heavily tested in placement interviews.
Syntax
python
class BankAccount:
bank_name = "State Bank" # class variable (shared)
def __init__(self, holder: str, balance: float = 0):
self.holder = holder # instance variable
self.__balance = balance # private (name mangling)
def deposit(self, amount: float) -> None:
if amount <= 0: raise ValueError("Amount must be positive")
self.__balance += amount
def withdraw(self, amount: float) -> bool:
if amount > self.__balance: return False
self.__balance -= amount
return True
@property
def balance(self) -> float: # getter
return self.__balance
def __str__(self): # string representation
return f"Account({self.holder}: ₹{self.__balance:,})"
@classmethod
def create_savings(cls, holder: str):
return cls(holder, balance=1000) # factory methodCommon Pitfalls
- Single underscore _var is a convention for 'protected'; double underscore __var causes name mangling (truly private). Know the difference.
- Python supports multiple inheritance — use Method Resolution Order (MRO) and super() carefully.
- Interview tip: The 4 pillars — Encapsulation (hiding data), Abstraction (hiding complexity), Inheritance (reusing code), Polymorphism (same interface, different behavior).
Real-World Example
A vehicle class hierarchy for a ride-sharing app:
example
python
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, id: str, capacity: int):
self.id = id
self.capacity = capacity
self._is_available = True
@abstractmethod
def fare_per_km(self) -> float:
pass
def estimate_fare(self, distance_km: float) -> float:
return round(distance_km * self.fare_per_km(), 2)
@property
def is_available(self): return self._is_available
class Auto(Vehicle):
def fare_per_km(self): return 12.0
class Cab(Vehicle):
def __init__(self, id, capacity, is_premium=False):
super().__init__(id, capacity)
self.is_premium = is_premium
def fare_per_km(self): return 18.0 if not self.is_premium else 28.0
auto = Auto("AUTO-042", capacity=3)
cab = Cab("CAB-117", capacity=4, is_premium=True)
print(auto.estimate_fare(5)) # ₹60.0
print(cab.estimate_fare(5)) # ₹140.0