7.1 Classes, Objects, __init__, self & Class vs. Instance Attributes
Build a crystal-clear OOP foundation! Learn how one class blueprint creates independent objects in RAM, what self actually is, and how to avoid the mutable class-attribute trap.
1. Blueprint vs. House: What Is OOP?
Think of a Class as an architect's blueprint for a house. You cannot live inside a blueprint — but you can stamp out 100 real, independent houses (Objects / Instances) from that single blueprint, each with its own paint color and owner!
- Attributes = Data attached to an object (
owner,balance). - Methods = Functions attached to a class that operate on that object (
deposit(),withdraw()).
2. Writing Your First Class & Demystifying self
Freshers always ask: "Why do I have to write self as the first parameter of every method?"
Because when you call acc1.deposit(200), Python secretly translates it to:
BankAccount.deposit(acc1, 200) — passing acc1 in as self so the method knows which object's balance to update!
class BankAccount:
bank_name = "BigOBank" # Class attribute (shared by ALL accounts)
def __init__(self, owner, balance=0):
self.owner = owner # Instance attribute (unique to THIS object)
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
acc1 = BankAccount("Aarav", 500)
acc2 = BankAccount("Riya", 1200)
acc1.deposit(250)
print(acc1.owner, acc1.balance) # Aarav 750
print(acc2.owner, acc2.balance) # Riya 1200 (completely independent!)
3. Beginner Trap: Never Put a Mutable List as a Class Attribute!
# ✗ BUG: All Dog instances accidentally share ONE tricks list!
class BrokenDog:
tricks = []
# ✓ FIX: Initialize mutable attributes inside __init__ on self!
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # Each dog gets its own private list!
4. @classmethod vs. @staticmethod
| Decorator | First Param | When to Use |
|---|---|---|
| (normal method) | self (instance) | Needs to read or modify this specific object's data |
@classmethod | cls (the class) | Alternative constructors (e.g., User.from_json(raw_dict)) |
@staticmethod | (none) | Helper function logically grouped inside the class (e.g., is_valid_email(s)) |
5. Interactive Trace: Creating Objects & Calling Methods
Quick Quiz: Module 7.1 — Classes, Objects & self
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.