Start learning free

LESSON 283 OF 673 · FUNCTIONS & CLASSES

The __init__ Method in Python

Lesson

TL ; DR:

  • The __init__ method is Python's constructor — it runs automatically when you create an object, and it's where you set up the object's attributes.


  • The first parameter is always self (the object being created), followed by whatever arguments you want to accept:

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

  • Then create objects with arguments: Dog("Rex", 4) — the __init__ method fills in the attributes for you.



Full lesson:

In the previous lesson you set attributes one at a time after creating the object:

dog = Dog()
dog.name = "Rex"
dog.age = 4

That works, but it's verbose and easy to forget. The __init__ method lets you initialize the attributes the moment Dog(...) is called.


Defining __init__

Two things are special about Python's constructor:

  • It's named __init__ (with two underscores on each side — these are called "dunders").

  • Its first parameter is self, which Python automatically passes when you create an object. self refers to the object being created.

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

Inside __init__, self.name = name means "store the parameter name as an attribute on this new object".


Calling the constructor

Once you've defined __init__ with arguments, every Dog(...) call must provide them:

rex  = Dog("Rex", 4)
luna = Dog("Luna", 7)

You don't pass self when calling — Python provides it for you. By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


Your task

Inside the Dog class, define an __init__ method that takes self, name, and age, and assigns the parameters to attributes using self.. Then below the class, create two dogs:

rex  = Dog("Rex", 4)
luna = Dog("Luna", 7)

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check