Object-oriented programming (OOP) groups data and the functions that work on it into classes.
- A class is a blueprint (
Student) - An object is one thing made from it (
asha = Student("Asha"))
init and self
__init__ runs when an object is created and sets its attributes. self is the object itself — the first parameter of every method.
Attributes
- Instance attributes:
self.name— different for each object - Class attributes: defined in the class body — shared by all objects
Methods
- Normal methods use
self @classmethodgets the class (cls) — useful for alternative constructors@staticmethod— a helper that needs neither
Properties
@property lets a method be read like an attribute and is used for validation with a setter.
Special (dunder) methods
__str__ (for print), __repr__ (for debugging), __len__, __eq__, __lt__, __add__ — make objects work with built-in operations.
dataclasses
@dataclass writes __init__, __repr__ and __eq__ for you.
Example
class BankAccount:
bank_name = "AgyanBank" # class attribute
def __init__(self, owner: str, balance: float = 0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
return self
def __str__(self):
return f"{self.owner}: ₹{self._balance:,.2f}"
asha = BankAccount("Asha", 1000)
ravi = BankAccount("Ravi")
asha.deposit(500).deposit(250)
ravi.deposit(2000)
print(asha)
print(ravi)
print(asha.balance, BankAccount.bank_name)
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
print(Product("Pen", 20))
Output: Asha: ₹1,750.00, Ravi: ₹2,000.00, 1750 AgyanBank, Product(name='Pen', price=20)