__init__ is a special method that runs automatically when you create a new object from your class.Mental model: Think of
__init__ as the assembly line at a factory. The blueprint (your class) says what parts exist, but __init__ is where each specific unit gets its serial number and configuration.Why it matters: Real programs are full of things that need setup: a bank account needs an owner's name; a game character needs health points. Without
__init__, you'd have to manually set every attribute after creating the object, which is error-prone and messy.The self parameter
class Dog:
def __init__(self, name):
# 'name' is the input argument
# we save it to THIS specific dog object as an attribute
self.name = name
def speak(self):
print(f"{self.name} says Woof!")
# Create two different dogs using the same blueprint.
dog1 = Dog("Rex")
dog2 = Dog("Bella")
dog1.speak()
print(dog2.name)self is a convention for the first parameter of every method. It refers to the specific instance that called it.When you call
dog1.speak(), Python passes dog1 as the value of self. This allows different objects created from the same class (like Rex and Bella) to hold completely independent data without stepping on each other's toes.Setting up with defaults
class Player:
def __init__(self, name="Hero", level=1):
self.name = name
self.level = level
guest_player = Player()
custom_player = Player("ShadowKnight", 42)
print(guest_player.name) # Hero
print(custom_player.name)# ShadowKnightDefault values let you create objects with minimal information. The
guest_player example shows how Python fills in the gaps when you don't provide arguments.