Skip to main content
Albero Academy

Constructors (__init__)

Initialise object state cleanly when instances are created.

Object-Oriented Programming8 min

The __init__ method — the constructor — runs automatically the moment you create an instance. Its job is to set up the object's starting state by assigning attributes to self.

Setting up state

__init__ with defaults
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance # default balance of 0
acc = Account("Ravi") # balance defaults to 0
acc2 = Account("Ana", 5000) # explicit starting balance

Validating in the constructor

A constructor is a good place to reject invalid state, so an object can never exist in a broken form:

guarding on creation
class Account:
def __init__(self, owner, balance=0):
if balance < 0:
raise ValueError("balance cannot be negative")
self.owner = owner
self.balance = balance

Key takeaways

  1. 01__init__ is the constructor, called automatically on instance creation.
  2. 02It sets the starting attributes via self.
  3. 03Parameters can have defaults for optional initial state.
  4. 04Validate arguments here so objects never exist in a broken state.
  5. 05It initialises the object and returns None (never return a value).

Finished this chapter?

Mark it complete to track your progress through Python.