logo

The __init__ Method

When you create an object, you usually want to give it some initial data. That's what __init__ does - it runs automatically when an object is created.

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Now when you create a Dog, you must provide name and age:

buddy = Dog("Buddy", 3)
print(buddy.name)  # Buddy

The self parameter refers to the object being created. self.name = name stores the name on that specific object.

Every class you write will have __init__. It's how you set up your objects with the data they need.

I cover __init__ patterns in my Python OOP course.