The __init__ Constructor
Automate object setup so every object starts with the right data.
Introduction
So far you have set attributes manually after creating an object. That works, but it is error-prone -- you might forget to set one, or spell it wrong. The __init__ method automates this. It runs automatically every time you create an object, so your objects always start in a valid state.
What is __init__?
__init__ is a special method (called a constructor) that Python calls automatically when you create an object. Its job is to set up the initial values -- the attributes -- that the object needs.
Key idea: You never call __init__ yourself. Python calls it for you behind the scenes when you write ClassName().
Before __init__ (The Problem)
Without a constructor, you must manually assign every attribute after creating the object. This is tedious and easy to get wrong.
class Student:
pass
s = Student()
s.name = "Alice" # manual, error-prone
s.age = 20 # what if you forget this line?
With __init__ (The Solution)
The constructor handles everything in one step. You pass the data when creating the object, and __init__ stores it automatically.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s = Student("Alice", 20)
print(s.name) # Alice
print(s.age) # 20
The self Parameter
self refers to the specific object being created. When you write self.name = name, you are saying: "store the value of name inside this particular object."
Think of it this way: If you create two students, each one has its own self. The first student's self.name is "Alice", and the second student's self.name is "Bob". They do not interfere with each other.
Default Values in __init__
You can give parameters default values, just like regular functions. If the caller does not provide a value, the default is used.
class Product:
def __init__(self, name, price, stock=0):
self.name = name
self.price = price
self.stock = stock
p1 = Product("Laptop", 999) # stock defaults to 0
p2 = Product("Mouse", 25, 100) # stock is 100
print(p1.stock) # 0
print(p2.stock) # 100
Complete Example: BankAccount
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
def display(self):
print(f"Account owner: {self.owner}, Balance: ${self.balance}")
acc = BankAccount("Alice", 500)
acc.display() # Account owner: Alice, Balance: $500
acc.deposit(200) # Deposited $200. New balance: $700
Real-World Connection
Every bank account created needs an owner name and a starting balance. The constructor ensures this happens automatically -- no bank account can exist without these essential details, just like in the real world where you cannot open an account without providing your information.
OOP Terms
- Constructor: A special method that initializes an object. In Python, this is
__init__. - Initialization: The process of setting up an object's starting state with its initial attribute values.
- self: A reference to the current object instance. It lets you store data that belongs to that specific object.
Best Practices
- Always define
__init__if your class needs attributes -- do not rely on manual assignment. - Use default values for optional parameters to make object creation flexible.
- Keep
__init__focused on setting up attributes. Avoid putting complex logic in it.
Common Mistakes
- Forgetting
selfas the first parameter -- Python will raise a TypeError. - Writing
name = nameinstead ofself.name = name-- the value will not be stored on the object. - Calling
__init__manually -- Python calls it for you when you create an object.
Practice Exercises
- Create a
Bookclass with an__init__that takestitle,author, andpages. Create two books and print their details. - Create a
Carclass wherecolordefaults to"White". Create one car with a custom color and one without. - Create a
Rectangleclass withwidthandheightin__init__, and anarea()method that returns the area.
Summary
__init__is Python's constructor -- it runs automatically when you create an object.selfrefers to the specific object being created and lets you store attributes on it.- You can use default parameter values to make some arguments optional.
- Constructors ensure every object starts in a valid, predictable state.