__init__()

A method called automatically when an object is created. It stores the object’s initial data, its attributes.

Returns
Always None. The call to the class itself returns the finished object.
On this page

Example

#
Python
class Student:
    def __init__(self, name, points=0):
        self.name = name
        self.points = points
        self.level = points // 100 + 1

emma = Student("Emma", 250)
jack = Student("Jack")

print(emma.name, emma.points, emma.level)
print(jack.name, jack.points, jack.level)
print(vars(emma))
Resultsaved result, you can check it
Emma 250 3
Jack 0 1
{'name': 'Emma', 'points': 250, 'level': 3}

Definition and usage

#

The __init__ method, commonly called the constructor, prepares a new object for use. Python calls it by itself, right after the object is created, when you write e.g. Student("Emma", 250). The arguments given in parentheses after the class name land in __init__, whose job is to store them as attributes of the object: self.name = name.

The first parameter, self, is the freshly created object, which Python passes in automatically. The remaining parameters work like in an ordinary function: they can have default values and can be given by name. Attributes do not have to be a copy of the arguments either, they can also be computed from them, for example a level based on points.

Strictly speaking, the object is created a moment earlier, in the __new__ method, which you rarely need to touch. __init__ only initializes it and must return None; trying to return another value ends in a TypeError. It is a good place to validate data: an exception raised inside __init__ means the call to the class does not return an object, so invalid data never reaches the rest of the program.

Syntax

#
Syntax
class Name:
    def __init__(self, param, optional_param=value):
        self.attribute = param

Parameters

#
  • self

    the new object

    The object being created. Python passes it in automatically, so you do not supply it when calling.
  • other parameters

    any values

    The arguments given when creating the object, e.g. Student("Emma", 250). They can have default values.

More examples

#
Validating data when creating an object
Python
class Course:
    def __init__(self, title, modules):
        if modules <= 0:
            raise ValueError("A course must have at least one module")
        self.title = title
        self.modules = modules

python = Course("Python", 12)
print(python.title, python.modules)

try:
    Course("Empty course", 0)
except ValueError as error:
    print("Error:", error)
Resultsaved result, you can check it
Python 12
Error: A course must have at least one module
A trap: a list as a default value
Python
class Team:
    def __init__(self, name, members=[]):
        self.name = name
        self.members = members

red = Team("Red")
blue = Team("Blue")
red.members.append("Emma")
print(blue.members)

class SafeTeam:
    def __init__(self, name, members=None):
        self.name = name
        self.members = list(members) if members is not None else []

red = SafeTeam("Red")
blue = SafeTeam("Blue")
red.members.append("Emma")
print(blue.members)
Resultsaved result, you can check it
['Emma']
[]

The default list is created only once, when the method is defined, so every Team object shares the same list. SafeTeam creates a new list for each object.

Good practices

#
  • Set all of an object’s attributes in __init__, even if they start out as None. That way it is immediately clear what data the object holds.
  • Do not use lists or dictionaries as default parameter values. Write None instead and create the new collection inside the method.
  • When a class is mainly meant to store data, @dataclass will generate __init__ for you.

Related entries

#

Spotted a mistake or missing an example? Write to us.