__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 value passed in.
# Store it on this dog:
self.name = name
# Two dogs from the same blueprint
dog1 = Dog("Rex")
dog2 = Dog("Bella")
print(dog1.name)
print(dog2.name)self is the name everyone gives the first parameter of __init__ (and, from the next lesson, of the other methods you write). It refers to the specific instance being set up.When you write
Dog("Rex"), Python first makes a new, empty dog. Then it runs __init__ for you, with that new dog as self and "Rex" as name. 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.