SyntaxPilot
Courses/Python/Lesson 21

Python · Lesson 21 of 40 · 11 min

OOP 1: classes, objects, __init__

queued

These are the notes for Python episode 21, the start of object oriented programming (OOP). Until now Python gave us its own types: numbers, strings, lists, dictionaries. In this episode the chai shop's khata (credit book) from episode 20, built from dictionaries, breaks because of one typo, and we invent our own type: a class. You will learn what a class and an object are, attributes, __init__, what self really is, methods, why forgetting self gives a confusing error, __str__ for printing, and the difference between class attributes and instance attributes, including the shared-list trap. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: a khata of dictionaries

In episode 20 every customer in the khata was a dictionary: a name and a credit amount. With two hundred customers, that's two hundred dictionaries. One of them was typed in a hurry:

asha = {"name": "Asha", "credit": 120}
ravi = {"nmae": "Ravi", "credit": 50}

# ... 200 lines later ...
for c in [asha, ravi]:
    print(c["name"], "owes", c["credit"])

Output:

Asha owes 120
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(c["name"], "owes", c["credit"])
          ~^^^^^^^^
KeyError: 'name'

The traceback points at line 6, the evening report. But the real mistake is on line 2: "nmae". Python didn't complain when we made it, because a dictionary accepts any key you give it.

Why it fails:

  1. A dictionary has no fixed shape. Nothing says every customer must have a name and a credit.
  2. The code that works with customers (adding credit, taking payments) lives somewhere else, in loose functions that accept any dictionary.

What we want: one fixed design for a customer, that every customer is made from, and that carries its own actions. That design is a class.

Class and object: a printed form

At a bank counter In Python
The blank form design: Name: ____ Balance: ____ class Customer: the class, the blueprint
Each filled form: Asha's, Ravi's, Meena's asha = Customer(...) an object (also called an instance)
The fields filled in: Name: Asha asha.name an attribute: the object's own data
What the clerk can do: deposit, withdraw asha.pay(100) a method: an action the object can do
  • A class is a design. It decides which data every object has and what it can do. Writing a class creates a new type, just like int or str.
  • An object is one thing made from the class. One class, as many objects as you like.
  • Attributes are the data stored on an object.
  • Methods are functions that belong to the class and act on its objects.

Other everyday pairs: a cookie cutter (class) and cookies (objects); a house blueprint (class) and the houses built from it (objects).

Your first class

class Customer:
    pass

asha = Customer()
ravi = Customer()

print(type(asha))
print(asha is ravi)

Output:

<class '__main__.Customer'>
False
  • class is the keyword, Customer the name, then a colon. The body is indented.
  • pass means "nothing here yet": a class body can't be empty.
  • You make an object by calling the class like a function: Customer().
  • type(asha) is __main__.Customer: a brand-new type, made by us. (__main__ is the name of the file being run; see episode 19.)
  • asha is ravi is False: two separate objects.

Naming convention: class names use CapitalWords (also called PascalCase): Customer, BankAccount, ChaiOrder. Variables and functions stay snake_case.

Attributes, one by one (still risky)

You can attach data to an object with a dot:

class Customer:
    pass

asha = Customer()
asha.name = "Asha"
asha.credit = 120

ravi = Customer()
ravi.name = "Ravi"

print(asha.name, asha.credit)
print(ravi.name, ravi.credit)

Output:

Asha 120
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    print(ravi.name, ravi.credit)
                     ^^^^^^^^^^^
AttributeError: 'Customer' object has no attribute 'credit'

We forgot to set Ravi's credit. Each object holds only what we put in it. Filling in the boxes one by one after creating the object is as risky as the dictionary was. We need the form filled in at the moment the object is created.

__init__: fill the form at the counter

A bank that hands out blank forms "to fill in later" ends up with half-empty forms. So the clerk fills the form at the counter, the moment the account is opened, and refuses a form without a name.

In Python that clerk is a special method called __init__ (two underscores, init, two underscores; short for initialise). Python runs it automatically every time you create an object.

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

asha = Customer("Asha", 120)
ravi = Customer("Ravi")

print(asha.name, asha.credit)
print(ravi.name, ravi.credit)

Output:

Asha 120
Ravi 0
  • Customer("Asha", 120) passes "Asha" and 120 to __init__.
  • credit=0 is a default parameter (episode 13): Ravi gets 0.
  • Every customer is now guaranteed to have both name and credit.

And if someone forgets the name:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

meena = Customer()

Output:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    meena = Customer()
TypeError: Customer.__init__() missing 1 required positional argument: 'name'

The mistake is caught on the very line that made it. Compare that with the dictionary, which crashed two hundred lines later.

__init__ is often called the constructor (strictly, Python builds the object first and __init__ then fills it in, but everyone uses the word).

What is self?

Slow down the line asha = Customer("Asha", 120). Python does three things:

Step What happens
1 Python makes a new, empty object of type Customer.
2 It calls __init__(that_object, "Asha", 120). Inside __init__, the first parameter, self, is that new object.
3 The name asha now points at the finished object.

So self simply means "the object this call is working on".

  • self.name = name stores the value on the object, so it lives as long as the object does.
  • name = name (without self.) would just create a local variable inside __init__ that disappears when __init__ ends (local scope, episode 14). The object would get nothing:
class Tea:
    def __init__(self, kind):
        kind = kind

t = Tea("masala")
print(t.kind)

Output:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(t.kind)
          ^^^^^^
AttributeError: 'Tea' object has no attribute 'kind'
  • self is not a keyword, just a very strong convention. Always call it self.
  • Every method's first parameter is self.

Methods: data and actions together

A function written inside a class is called a method. The customer's actions now live right next to the customer's data:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def add(self, amount):
        self.credit += amount

    def pay(self, amount):
        self.credit -= amount

asha = Customer("Asha", 120)
asha.add(30)
asha.pay(100)
print(asha.name, "owes", asha.credit)

Output:

Asha owes 50

120 + 30 − 100 = 50. Notice: asha.add(30) passes only the amount. Where does self come from?

How asha.add(30) really works

When you write asha.add(30), Python turns it into Customer.add(asha, 30). The object before the dot becomes self automatically. You can even write the long form yourself:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def add(self, amount):
        self.credit += amount

asha = Customer("Asha", 120)
Customer.add(asha, 30)
print(asha.credit)
asha.add(30)
print(asha.credit)
print(asha.__dict__)
print(isinstance(asha, Customer))

Output:

150
180
{'name': 'Asha', 'credit': 180}
True
  • Both calls do the same thing; the short form asha.add(30) is what you always write.
  • asha.__dict__ shows the object's own attributes: under the hood, an object keeps its attributes in a dictionary. The class gives that dictionary a fixed, guaranteed shape.
  • isinstance(asha, Customer) checks whether an object was made from a class.

Forgetting self

The classic beginner mistake:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def add(amount):
        self.credit += amount

asha = Customer("Asha", 120)
asha.add(30)

Output:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    asha.add(30)
    ~~~~~~~~^^^^
TypeError: Customer.add() takes 1 positional argument but 2 were given

"Two were given? We passed one!" The hidden one is the object itself, which Python always passes first. add only had room for one parameter. Put self back: def add(self, amount):.

That's the whole idea of a class: data, and the actions on that data, live together in one place. You just invented classes and objects.

Printing objects: __str__

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

asha = Customer("Asha", 120)
print(asha)

Output (the number is the object's address in memory, and it is different on every run):

<__main__.Customer object at 0x7fe6af4df0e0>

Correct, but useless to a shopkeeper. The fix is another special method, __str__. It returns the text that print() (and str()) should show:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def __str__(self):
        return f"{self.name} owes Rs {self.credit}"

asha = Customer("Asha", 120)
print(asha)
print("Today:", asha)

Output:

Asha owes Rs 120
Today: Asha owes Rs 120
  • __str__ must return a string; it doesn't print anything itself.
  • Methods with two underscores on both sides (__init__, __str__) are called dunder methods ("double underscore") or magic methods. You don't call them yourself: Python calls them at the right moment (__init__ on creation, __str__ when printing). Episode 23 covers many more.

Class attributes vs instance attributes

  • An instance attribute is set on one object, usually self.something = ... in __init__. Each object has its own.
  • A class attribute is a variable written directly inside the class body (not inside a method). There is one copy, shared by every object.

A good use of a class attribute: a counter shared by all objects.

class Counter:
    total = 0                  # class attribute: shared

    def __init__(self, name):
        self.name = name       # instance attribute: own
        Counter.total += 1

a = Counter("gate 1")
b = Counter("gate 2")
print(a.name, b.name, Counter.total)

Output:

gate 1 gate 2 2

How Python finds an attribute

When you read obj.x, Python looks on the object first, and if it isn't there, on the class. That rule explains both the trap below and the quiz.

The shared-list trap

Let's give every customer an orders list, as a class attribute:

class Customer:
    orders = []          # class attribute

    def __init__(self, name):
        self.name = name

asha = Customer("Asha")
ravi = Customer("Ravi")
asha.orders.append("chai")

print("Ravi's orders:", ravi.orders)

Output:

Ravi's orders: ['chai']

Ravi never ordered! asha.orders looked on the object, found nothing, then found the single list on the class. append changed that one shared list, and every customer sees it.

The fix: create the list inside __init__, so each customer gets their own. Keep class attributes for things that really are shared and don't change, like the shop's name:

class Customer:
    shop = "Raju Chai"    # shared by all: fine

    def __init__(self, name):
        self.name = name
        self.orders = []  # one list per customer

asha = Customer("Asha")
ravi = Customer("Ravi")
asha.orders.append("chai")

print("Ravi's orders:", ravi.orders)
print(asha.shop, ravi.shop)

Output:

Ravi's orders: []
Raju Chai Raju Chai

Rule: lists, dictionaries and sets (mutable values) belong in __init__ with self., never in the class body.

Common mistakes

Mistake What you see Why Fix
{"nmae": "Ravi"} then c["name"] KeyError: 'name' (far from the typo) a dict has no fixed shape a class with __init__
Customer() with no name TypeError: Customer.__init__() missing 1 required positional argument: 'name' __init__ needs it Customer("Meena")
def add(amount): inside a class TypeError: Customer.add() takes 1 positional argument but 2 were given the object is always passed as self def add(self, amount):
reading ravi.credit that was never set AttributeError: 'Customer' object has no attribute 'credit' the attribute doesn't exist on that object set every attribute in __init__
a typo: ravi.nmae AttributeError: 'Customer' object has no attribute 'nmae' no such attribute spell it as in __init__
kind = kind in __init__ AttributeError: 'Tea' object has no attribute 'kind' a local variable, not stored on the object self.kind = kind
print(asha) no error: <__main__.Customer object at 0x...> no __str__ def __str__(self): return ...
orders = [] in the class body no error: every customer shares one list a class attribute is one copy self.orders = [] in __init__
__str__ that prints instead of returning TypeError: __str__ returned non-string (type NoneType) print() needs a string back return f"..."

Mini project: a khata of Customer objects

The khata from episode 20, rebuilt with a class: __init__, add, pay and __str__. The khata is just a list of objects, and max() with a key (episode 17) finds who to collect from first.

# Mini project: a khata of Customer objects
class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def add(self, amount):
        self.credit += amount

    def pay(self, amount):
        self.credit -= amount

    def __str__(self):
        return f"{self.name:<6} Rs {self.credit}"

khata = [Customer("Asha", 120), Customer("Ravi", 50), Customer("Meena")]
khata[1].add(200)
khata[0].pay(120)

for c in khata:
    print(c)
top = max(khata, key=lambda c: c.credit)
print("Collect first from:", top.name)

Output:

Asha   Rs 0
Ravi   Rs 250
Meena  Rs 0
Collect first from: Ravi

{self.name:<6} pads the name to 6 characters, left-aligned, so the amounts line up (format specs, episode 5).

Extend it: add a method is_clear() that returns True when the credit is zero:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

    def is_clear(self):
        return self.credit == 0

asha = Customer("Asha")
ravi = Customer("Ravi", 250)
print(asha.is_clear(), ravi.is_clear())

Output:

True False

Next step: save the khata to JSON (episode 20) by turning each object into a dict, e.g. {"name": c.name, "credit": c.credit}.

Practice

1. A Student class with a name and a list of marks, a method average(), and a __str__. Make three students and print the topper with max().

Solution
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def average(self):
        return sum(self.marks) / len(self.marks)

    def __str__(self):
        return f"{self.name}: {self.average():.1f}"

students = [Student("Asha", [90, 85, 92]), Student("Ravi", [70, 88, 79]), Student("Meena", [95, 91, 89])]
for s in students:
    print(s)
topper = max(students, key=lambda s: s.average())
print("Topper:", topper.name)

Output:

Asha: 89.0
Ravi: 79.0
Meena: 91.7
Topper: Meena

2. A BankAccount with deposit() and withdraw(); withdraw raises a ValueError (episode 18) when the balance is too low. Give it a __str__.

Solution
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient balance")
        self.balance -= amount

    def __str__(self):
        return f"{self.owner}: Rs {self.balance}"

acc = BankAccount("Asha", 1000)
acc.deposit(500)
acc.withdraw(300)
print(acc)
try:
    acc.withdraw(5000)
except ValueError as e:
    print("Error:", e)

Output:

Asha: Rs 1200
Error: Insufficient balance

3. Count how many objects of a class have been created, using a class attribute.

Solution
class Counter:
    total = 0                  # class attribute: shared

    def __init__(self, name):
        self.name = name       # instance attribute: own
        Counter.total += 1

a = Counter("gate 1")
b = Counter("gate 2")
print(a.name, b.name, Counter.total)

Output:

gate 1 gate 2 2

Note Counter.total += 1, not self.total += 1: the second would create a new instance attribute on that one object instead of changing the shared one.

4. Why does this crash, and how do you fix it?

class Tea:
    def __init__(self, kind):
        kind = kind

t = Tea("masala")
print(t.kind)
Solution

kind = kind assigns a local variable inside __init__; nothing is stored on the object, so print(t.kind) raises AttributeError: 'Tea' object has no attribute 'kind'. Fix: self.kind = kind.

Quick quiz

1. The video's quiz: what does this print?

class Cup:
    size = "small"
    def __init__(self, tea):
        self.tea = tea

a = Cup("masala")
b = Cup("ginger")
a.size = "large"
print(a.tea, a.size, b.size)
Answer
masala large small

a.size = "large" creates a new attribute on a only. b has no size of its own, so Python looks on the class and finds "small".

2. What does this print?

class Glass:
    def __init__(self):
        self.ml = 0
    def fill(self, ml):
        self.ml += ml

a = Glass()
b = a
b.fill(100)
print(a.ml)
Answer

100. b = a doesn't copy the object: both names point at the same glass (like two names for one list, episode 10).

3. A method is defined as def add(amount):. Calling asha.add(30) says "takes 1 positional argument but 2 were given". What's the second argument?

Answer

The object itself, asha. asha.add(30) runs as Customer.add(asha, 30). The method needs self as its first parameter.

4. When does __init__ run?

Answer

Automatically, every time an object is created: Customer("Asha") makes the object and then calls __init__ on it.

Interview questions

  1. What is a class, and what is an object? A class is a blueprint that defines a new type: the data (attributes) and behaviour (methods) its objects have. An object (instance) is one concrete thing created from a class.
  2. What does __init__ do? It initialises a new object: Python calls it right after creating the object, passing the object as self plus the arguments given to the class call. It's commonly called the constructor.
  3. What is self? The first parameter of every instance method: a reference to the object the method was called on. obj.method(x) is executed as Class.method(obj, x).
  4. Is self a keyword? No, it's a convention; any name works, but always use self.
  5. Instance attribute vs class attribute? Instance attributes belong to one object (self.x in __init__); a class attribute is defined in the class body and shared by all instances. Attribute lookup checks the instance first, then the class.
  6. Why is a mutable class attribute (like orders = []) dangerous? All instances share the same list, so changing it through one object changes it for all. Create mutable attributes in __init__.
  7. What are dunder (magic) methods? Methods named __like_this__ that Python calls automatically in certain situations: __init__ on creation, __str__ for print()/str(), and many more (__len__, __eq__, ...).
  8. What is the default output of print(obj) without __str__? Something like <__main__.Customer object at 0x...>: the class name and the object's memory address.
  9. Why use classes instead of dictionaries? A class gives every object the same guaranteed shape (mistakes are caught at creation), keeps related behaviour next to the data, and creates a named type you can check with isinstance.

Glossary

Term Meaning Example
OOP Object oriented programming: building programs from objects that hold data and behaviour the khata of Customer objects
Class A blueprint that defines a new type class Customer:
Object / instance One thing created from a class asha = Customer("Asha")
Instantiate To create an object from a class Customer("Ravi")
Attribute Data stored on an object (or class) asha.name
Instance attribute An attribute belonging to one object, usually set with self. self.credit = credit
Class attribute A variable in the class body, shared by all objects shop = "Raju Chai"
Method A function defined inside a class def pay(self, amount):
self The object a method is working on; always the first parameter self.credit += amount
__init__ The method Python runs automatically when an object is created def __init__(self, name):
Constructor Common name for __init__: it sets up a new object Customer("Asha", 120)
__str__ Returns the text print() and str() show for an object return f"{self.name} owes ..."
Dunder method A "double underscore" (magic) method Python calls for you __init__, __str__
pass A statement that does nothing; a placeholder for an empty body class Customer: pass
type() Returns an object's type type(asha) → <class '__main__.Customer'>
isinstance() Checks whether an object was made from a class isinstance(asha, Customer) → True
__dict__ The dictionary holding an object's own attributes {'name': 'Asha', 'credit': 180}
Memory address Where an object lives in RAM; shown as 0x..., different each run <... object at 0x7fe6af4df0e0>
PascalCase (CapitalWords) Naming style for classes BankAccount
AttributeError Reading an attribute that the object doesn't have ravi.nmae
KeyError Reading a dictionary key that doesn't exist c["name"] on {"nmae": ...}
TypeError Wrong number or type of arguments Customer() with no name
Mutable A value that can be changed in place a list, a dict
Khata A shop's credit book: who owes how much khata = [Customer(...), ...]

Summary

  • Dictionaries have no fixed shape: a key typo crashes far away from the mistake.
  • A class is the design (a new type); an object is one thing made from it.
  • __init__ runs on creation and sets every attribute; a missing argument is caught on the spot.
  • self is the object the method is working on; asha.add(30) runs as Customer.add(asha, 30).
  • Methods are functions inside a class: data and actions live together. Forget self and you get "takes 1 positional argument but 2 were given".
  • __str__ returns the text print() shows; without it you see a memory address.
  • Class attributes are shared by all objects; mutable values (lists, dicts) belong in __init__ with self..

Next episode: OOP part 2. The shop needs a VIP customer: a customer plus a discount. Copying the whole class would bring back the copy-paste problem, so we invent inheritance and polymorphism.