Notes › Python
OOP in Python
General OOP ideas are in Four Pillars of OOP; this note shows how Python does them.
Class and object
class Student:
college = "PIET" # class attribute — shared by all students
def __init__(self, name, cgpa): # constructor
self.name = name # instance attributes — one per object
self.cgpa = cgpa
def is_eligible(self, cutoff=7.0):
return self.cgpa >= cutoff
s = Student("Asha", 8.2)
print(s.name, s.is_eligible()) # Asha True
print(Student.college)
self is the object the method was called on (Python passes it automatically).
Encapsulation
Python has no private keyword. By convention:
_balance— "internal, please don't touch"__balance— name-mangled to_Account__balance, harder to access by accident
Properties give getter/setter logic with attribute syntax:
class Account:
def __init__(self, balance):
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
acc = Account(100)
acc.balance = 50 # calls the setter
Inheritance and super()
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, I am {self.name}"
class Engineer(Person):
def __init__(self, name, stack):
super().__init__(name) # run the parent constructor
self.stack = stack
def greet(self): # overriding
return super().greet() + f" and I work with {self.stack}"
print(Engineer("Ravi", "MERN").greet())
isinstance(Engineer("x", "y"), Person) # True
Python supports multiple inheritance; the MRO (method resolution order, Engineer.__mro__) decides which parent method is used.
Polymorphism (duck typing)
"If it walks like a duck…" — Python cares about what methods an object has, not its class.
class Dog:
def speak(self): return "Woof"
class Cat:
def speak(self): return "Meow"
for animal in [Dog(), Cat()]:
print(animal.speak())
Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
# Shape() → TypeError: can't instantiate an abstract class
Dunder (magic) methods
| Method | Lets you write |
|---|---|
__str__ / __repr__ |
print(obj) / debug representation |
__len__ |
len(obj) |
__eq__, __lt__ |
a == b, a < b (sorting) |
__add__ |
a + b |
__getitem__ |
obj[i] |
__iter__, __next__ |
for x in obj |
__enter__, __exit__ |
with obj: |
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, o): return Point(self.x + o.x, self.y + o.y)
def __repr__(self): return f"Point({self.x}, {self.y})"
print(Point(1, 2) + Point(3, 4)) # Point(4, 6)
Class methods and static methods
class Date:
def __init__(self, d, m, y): self.d, self.m, self.y = d, m, y
@classmethod
def from_string(cls, s): # alternative constructor; gets the class
d, m, y = map(int, s.split("-"))
return cls(d, m, y)
@staticmethod
def is_leap(y): # utility; gets neither self nor cls
return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
Dataclasses (less boilerplate)
from dataclasses import dataclass
@dataclass
class Book:
title: str
price: float = 0.0
# __init__, __repr__ and __eq__ are generated for you
Decorators (functions that wrap functions)
def timer(fn):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.time() - start:.3f}s")
return result
return wrapper
@timer
def slow(): sum(range(10**6))
Interview one-liners
selfis explicit in Python;__init__initialises, it doesn't create (that's__new__).- Class attributes are shared; instance attributes belong to each object.
@staticmethodvs@classmethod: no access to the class vs receivescls.- Python has no method overloading by signature — use default/keyword arguments.
- Python uses duck typing for polymorphism.