Python · Module 07: Object-Oriented Programming (OOP)Tutorial 19 of 30

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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()).
Visual: One Class Blueprint (`BankAccount`) → Independent Objects in RAM (`self` Binds Each One)
class BankAccountbank = "BigOBank" (shared)def __init__(self, owner, bal)def deposit(self, amt)(The Blueprint)acc1 (self → 0x101)owner = "Aarav" | balance = 500acc2 (self → 0x208)owner = "Riya" | balance = 1200

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!

PYTHON
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!

PYTHON
# ✗ 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

DecoratorFirst ParamWhen to Use
(normal method)self (instance)Needs to read or modify this specific object's data
@classmethodcls (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

Tracing BankAccount Instantiation & self.deposit()
Interactive Line-by-Line Execution Trace · Step 1 of 3
1→acc = BankAccount("Aarav", 500)
2new_bal = acc.deposit(200)
3print(f"{acc.owner}: {new_bal}")
Variables in Memory
acc.owner"Aarav"str
acc.balance500int
Console Output
(nothing printed yet)
What just happened: __init__(self, 'Aarav', 500) runs automatically and attaches owner and balance to the new object.

Quick Quiz: Module 7.1 — Classes, Objects & self

Q1.When does `__init__` run in a Python class?
Q2.What does `self` refer to inside a method?
Q3.Where should per-object lists like `self.items = []` always be created?

Keep Exploring: Related Lessons & Tools

All Courses →