The __init__ Method
__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)
When you write Product("Soap", 120), Python:
- creates a new, empty
Productobject; - calls
__init__, passing the new object asself, then"Soap"and120; - 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
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)
"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)
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)
Notice __init__ also tidied the name (removing spaces and capitalising), so every Student stores names consistently.
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)
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)
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.selfis the new object; store data withself.attribute = value.- Use defaults, calculated attributes and validation to build complete, valid objects.
- Never use a list or dictionary as a default argument; use
Noneinstead. @dataclasscan generate__init__for simple data classes.
Tip: use the ← and → keys to move between pages.
