__init__ & self
Overview
The __init__ method is Python's constructor; it executes automatically the exact moment an object is instantiated to set up its initial state. The self parameter is omnipresent in OOP. It represents the specific, current instance of the object being manipulated. When you call an object's method, Python implicitly passes the object itself as the first argument, allowing the method to access and mutate that specific object's data.
Syntax
class BankAccount:
def __init__(self, owner, starting_balance=0):
# 'self' binds these variables to this specific object instance
self.owner = owner
self.balance = starting_balance
def deposit(self, amount):
# 'self' allows the method to access the object's balance
self.balance += amount
def get_statement(self):
return f"{self.owner} has USD {self.balance}"
# Creation triggers __init__ automatically
acc = BankAccount("Alice", 100)
# Python secretly translates this to BankAccount.deposit(acc, 50)
acc.deposit(50)
print(acc.get_statement()) # Alice has $150Common Pitfalls
- Believing
selfis a reserved Python keyword. It is not! It is strictly a convention. You could technically name itthisorme, but doing so will instantly mark you as an amateur to other Python developers. - Accepting parameters in
__init__but forgetting to bind them usingself.param = param. Once the constructor finishes, unbound variables vanish into the void.
Interview Questions
self in every instance method definition?Python follows the philosophy 'Explicit is better than implicit'. By requiring self, it makes it painfully obvious whether a variable being modified belongs to the object instance (self.var) or is just a local temporary variable (var).
Real-World Example
Default state initialization ensuring clean instance separation.
class GameServer:
def __init__(self, region):
self.region = region
self.status = "Booting"
# Initializing a list here ensures every server gets its OWN list,
# rather than sharing a global list.
self.active_players = []Check Your Knowledge
Test your understanding of __init__ & self with these quick questions.