Velamuvi AIAcademy

Lesson 3 of 15 · Classes and Objects

The __init__ Method

Learn what Python's __init__ method does, how to set up every new object with its starting data, use default values and reject bad values with clear errors.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What the __init__ method is and when Python calls it
  • How to give every new object its starting data
  • How to use default values in __init__
  • How to reject bad values when an object is created

The problem with setting attributes by hand

In the last lesson you created a dog and then attached its data one line at a time:

rex = Dog()
rex.name = "Rex"
rex.age = 3

That is three lines for every dog, and it is easy to forget one. A dog without a name would crash the program the moment a method tried to use self.name.

What you want is for every new dog to be set up correctly, automatically, the moment it is created. That is the job of __init__.

Meet __init__

The name has two underscores on each side. "init" is short for initialise, which means "prepare for first use". You will also hear it called the constructor.

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


rex = Dog("Rex", 3)
bella = Dog("Bella", 5)

print(rex.name, rex.age)
print(bella.name, bella.age)

Here is what happens, step by step, when Python runs rex = Dog("Rex", 3):

  1. Python creates a new, empty Dog object.
  2. Python calls __init__, passing the new object as self, "Rex" as name and 3 as age.
  3. self.name = name stores "Rex" on the new object. self.age = age stores 3.
  4. The finished object is given the name rex.

The arguments you write inside Dog(...) go straight to __init__, after self.

People say __init__ out loud as "dunder init". You will meet more dunder methods later in the course.

Why self.name = name?

That line confuses almost everyone at first, because the word name appears twice. They are two different things:

  • name on the right is the parameter: the value passed in, which disappears when __init__ finishes.
  • self.name on the left is an attribute stored on the object, which stays as long as the object exists.

So self.name = name means "copy the value that was passed in onto this object, so it is remembered". The names do not have to match, but matching them is the normal, readable style.

Attributes that do not come from arguments

__init__ can also set attributes that every new object starts with, without any argument.

Try it yourselfPython
class Student:
    def __init__(self, name):
        self.name = name
        self.marks = []
        self.is_enrolled = True


ada = Student("Ada")
alan = Student("Alan")
ada.marks.append(92)

print(ada.name, ada.marks, ada.is_enrolled)
print(alan.name, alan.marks, alan.is_enrolled)

Every student starts with an empty list of marks. Because self.marks = [] runs separately for each new student, each one gets their own list: adding a mark for Ada does not touch Alan's list.

Default values

__init__ works like a normal function, so its parameters can have defaults too.

Try it yourselfPython
class Course:
    def __init__(self, title, level="Beginner", hours=10):
        self.title = title
        self.level = level
        self.hours = hours

    def describe(self):
        return f"{self.title} ({self.level}, {self.hours} hours)"


python = Course("Python for Beginners", hours=16)
oop = Course("Python OOP", "Intermediate", 10)
sql = Course("SQL for Beginners")

print(python.describe())
print(oop.describe())
print(sql.describe())

Keyword arguments, like hours=16, work exactly as they do with functions.

The same warning applies as with any function: never use a list or dictionary as a default value. Use None and create the list inside __init__:

def __init__(self, name, tags=None):
    self.name = name
    self.tags = tags if tags is not None else []

Checking values as the object is created

__init__ is the perfect place to refuse bad data. If a value makes no sense, raise an error. The object is then never created, so a broken object can never exist.

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, balance=0):
        if balance < 0:
            raise ValueError("A new account cannot start with a negative balance")
        self.owner = owner
        self.balance = balance


account = BankAccount("Ada", 100)
print(account.owner, account.balance)

try:
    broken = BankAccount("Alan", -50)
except ValueError as error:
    print("Could not create the account:", error)

raise ValueError("...") stops __init__ and reports the problem. The try and except around it catch the error, so the program can carry on. You learned try and except in Python for Beginners.

Methods use what __init__ stored

Once __init__ has stored the data, every other method can rely on it being there.

Try it yourselfPython
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)


box = Rectangle(4, 3)
print(box.area())
print(box.perimeter())

__init__ does not return anything. It only sets up the object. Writing return with a value inside __init__ causes an error.

Common mistakes

Practice exercise

Write a class whose __init__ stores the starting data, uses a default value and refuses a bad price.

Your solutionPython
# Write a class called Product with an __init__ that takes name, price and quantity.
# quantity should default to 1.
# If price is negative, raise ValueError("Price cannot be negative").
# Add a method total(self) that returns price * quantity.


mug = Product("Mug", 250, 4)
pen = Product("Pen", 20)
print(mug.name, mug.total())
print(pen.name, pen.total())

try:
    Product("Broken", -5)
except ValueError as error:
    print(error)

# Output must be exactly:
# Mug 1000
# Pen 20
# Price cannot be negative
Knowledge check

When does Python call the __init__ method?

Summary

  • __init__ is called automatically every time a new object is created.
  • Its first parameter is self, the new object. The arguments you pass to the class come next.
  • self.name = name copies a value onto the object so it is remembered.
  • Use default values for optional settings, and raise an error to reject bad values.
  • Every other method can rely on the attributes that __init__ set up.

Next: the difference between data that belongs to one object and data shared by the whole class.

Finished reading? Tick it off to track your progress.