Syllabus Lesson 48 of 239 · Object-Oriented Python
Object-Oriented Python

Setting Up With __init__

Adding attributes one by one after creating an object gets tedious and easy to forget. The __init__ method fixes that. It runs automatically the moment you create an object, so you can hand in the starting values right away.

The first parameter of every method is always self, which is the object being built. You store data on it with self.attribute = value.

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

rex = Dog("Rex", 3)
print(rex.name)   # Rex
print(rex.age)    # 3

Notice you pass "Rex" and 3 when creating the object, but you do not pass self yourself. Python fills self in for you. These values stored on self are called instance attributes, and each object gets its own copy.

a = Dog("Ada", 2)
b = Dog("Bo", 7)
print(a.name, b.name)   # Ada Bo

You can also give a parameter a default so it is optional:

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

Define a class Book whose __init__ takes title and author and stores them as self.title and self.author. Create one book with title "Dune" and author "Herbert", stored in a variable called fav.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output