Classes & Objects
- Define classes with
classand initialize with__init__ - Create instances and access instance attributes
- Write instance methods that operate on
self - Understand the difference between class and instance state
Every serious framework — Django models, SQLAlchemy declarative base, Pydantic BaseModel, PyTorch nn.Module — is class-based. Understanding self, __init__, and method resolution order is what separates script writers from library authors.
- Mutable default arguments like
def __init__(self, items=[])— shared across instances; useNonesentinel instead. - Forgetting
selfon method calls or attribute reads — Python won't warn; you'll getNameErrorat runtime. - Overriding
__eq__without__hash__— silently breakssetanddictmembership.
A class is a blueprint. Each instance holds its own state.
Key pieces
__init__— runs when you create an instance; sets initial state onselfself— refers to the current instance__repr__— controls how the object prints
Try it
- Add a
transfer(self, other, amount)method that moves money between accounts. - Make
balancea property that can't go below zero.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Define a class
Rectanglewith__init__(self, width, height)storing both. Add a methodarea(self)that returns width × height. Then printRectangle(4, 5).area()— expected:20. - Exercise 2
Define a
Counterclass with__init__startingcountat 0. Addincrement(self)that bumps by 1,reset(self)that sets back to 0, andvalue(self)that returns the count. Then create one, increment 3 times, print value, reset, print value. Expected outputs:3then0. - Exercise 3
Define a
BankAccountwith__init__(self, owner, balance=0), methodsdeposit(amount)andwithdraw(amount)that update balance.withdrawshould raiseValueError("insufficient funds")if amount exceeds balance. Add__repr__returning"BankAccount(<owner>, ₹<balance>)". Then create one, deposit 500, print repr — expected line ends with₹1500).