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
class Account:def __init__(self, owner, balance=0):self.owner = ownerself.balance = balance # default balance of 0acc = Account("Ravi") # balance defaults to 0acc2 = 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:
class Account:def __init__(self, owner, balance=0):if balance < 0:raise ValueError("balance cannot be negative")self.owner = ownerself.balance = balance
Key takeaways
- 01__init__ is the constructor, called automatically on instance creation.
- 02It sets the starting attributes via self.
- 03Parameters can have defaults for optional initial state.
- 04Validate arguments here so objects never exist in a broken state.
- 05It initialises the object and returns None (never return a value).
