__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.
Example
#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))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
#class Name:
def __init__(self, param, optional_param=value):
self.attribute = paramParameters
#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
#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)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)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 asNone. That way it is immediately clear what data the object holds. - Do not use lists or dictionaries as default parameter values. Write
Noneinstead and create the new collection inside the method. - When a class is mainly meant to store data,
@dataclasswill generate__init__for you.
Related entries
#- classDefines a class: a template for objects that combines data with the functions that act on it.
- selfThe first parameter of a method: the object the method was called on. It gives access to that object’s attributes and other methods.
- super()Calls a method of the base class from inside the derived class, most often the __init__ constructor.
- @dataclassA decorator that generates __init__, __repr__, and __eq__ for a data-storing class, based on type-annotated fields.
- __str__() and __repr__()Methods that define an object’s text appearance: readable for the user (__str__) and technical for the programmer (__repr__).
Spotted a mistake or missing an example? Write to us.