Skip to content
Kuza Ndoto Academy

The __init__ Method

Beginner → IntermediateChapter 8 · Page 41 of 564 min readUpdated 15 Nov 2026

__init__ is the method Python runs automatically every time you create a new object. Its job is to set up the object's starting data, so every object begins life complete and valid.

How __init__ works

class Product:
    def __init__(self, name, price):
        print(f"Setting up {name}...")
        self.name = name
        self.price = price

soap = Product("Soap", 120)
print(soap.name, soap.price)
Setting up Soap... Soap 120

When you write Product("Soap", 120), Python:

  1. creates a new, empty Product object;
  2. calls __init__, passing the new object as self, then "Soap" and 120;
  3. gives you back the finished object, which we store in soap.

The double underscores on each side mark it as a special ("dunder") method that Python calls for you. You'll rarely call __init__ yourself.

Understanding self

self is simply the first parameter of every regular method, and it refers to the particular object being set up or used. self.price = price means "store this price on this object". The name self is a convention rather than a keyword, but every Python programmer uses it, so you should too.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

a = Product("Soap", 120)
b = Product("Bread", 65)
print(a.name, b.name)     # each object has its own name
Soap Bread
Common mistake

Forgetting self in the parameter list. Python still passes the object in automatically, so the arguments no longer fit:

class Product:
    def __init__(name, price):      # self is missing
        pass

Product("Soap", 120)
TypeError: Product.__init__() takes 2 positional arguments but 3 were given

"3 were given" counts the hidden self plus your two arguments. Another version of this mistake is writing name = name instead of self.name = name: that only creates a local variable that vanishes when __init__ ends.

Default values and calculated attributes

__init__ takes parameters like any function, so you can give them defaults and compute extra attributes from them.

class MatatuTrip:
    def __init__(self, route, fare, seats=14):
        self.route = route
        self.fare = fare
        self.seats = seats
        self.passengers = 0                 # every trip starts empty
        self.max_takings = fare * seats     # calculated from other values

town = MatatuTrip("Route 46", 100)
express = MatatuTrip("Route 111", 150, seats=33)

print(town.route, town.seats, town.max_takings)
print(express.route, express.seats, express.max_takings)
Route 46 14 1400 Route 111 33 4950

Validating data in __init__

Because every object passes through __init__, it's the perfect place to reject bad data. Raise an exception (see Raising Exceptions) so an invalid object is never created.

class Student:
    def __init__(self, name, age):
        name = name.strip()
        if not name:
            raise ValueError("Name cannot be empty")
        if not 10 <= age <= 100:
            raise ValueError(f"Unrealistic age: {age}")
        self.name = name.title()
        self.age = age

s = Student("  baraka otieno ", 19)
print(s.name, s.age)

try:
    Student("Achieng", 7)
except ValueError as error:
    print("Could not create student:", error)
Baraka Otieno 19 Could not create student: Unrealistic age: 7

Notice __init__ also tidied the name (removing spaces and capitalising), so every Student stores names consistently.

Common mistake

Never use a mutable default such as a list in __init__. The default list is created once and shared by every object that uses it:

class Cart:
    def __init__(self, items=[]):       # the same list every time!
        self.items = items

a = Cart()
b = Cart()
a.items.append("Milk")
print(b.items)
['Milk']

Use None as the default and create a fresh list inside: self.items = items if items is not None else [].

__init__ must not return a value

__init__ sets up an object; it doesn't produce one. If you return anything other than None, Python raises TypeError: __init__() should return None, not 'int' (or whatever type you returned). To create objects in different ways, use a @classmethod, shown in Methods & Attributes.

A shortcut: dataclasses

Many classes have an __init__ that only copies parameters onto self. The standard library's dataclasses module can write that boring code for you, plus a readable printout.

from dataclasses import dataclass, field

@dataclass
class Order:
    customer: str
    total: float
    items: list = field(default_factory=list)   # safe mutable default

order = Order("Halima", 850.0)
order.items.append("Chapati")
print(order)
Order(customer='Halima', total=850.0, items=['Chapati'])

The names followed by a colon and a type (customer: str) are called type hints. The @dataclass line is a decorator; you'll learn how those work in Decorators.

Key points

  • __init__ runs automatically when you create an object.
  • self is the new object; store data with self.attribute = value.
  • Use defaults, calculated attributes and validation to build complete, valid objects.
  • Never use a list or dictionary as a default argument; use None instead.
  • @dataclass can generate __init__ for simple data classes.
Up next · Object-Oriented PythonMethods & AttributesGive objects data and behaviour.
→

Tip: use the ← and → keys to move between pages.