Skip to main content

The __init__() Method

Every class has a built-in method named __init__(), and Python runs it each time the class is used to build a new object.

This is the place to give object properties their values, or to do any other work the new object needs when it is created.

Note: The call to __init__() happens automatically, once for every new object you create.

Example

A class named Person whose __init__() method stores a name and an age:

Prompt
Create a Person class using init() to assign name and age, then create an object and print both properties.
Output: complete Python program

Why Use __init__()?

Leave out __init__() and each object's properties have to be set by hand, one at a time:

With __init__(), the starting values go in right when the object is created, which is much simpler:

Example

A class with no __init__():

Prompt
Create a Person class without init(), manually set name and age properties, and print them.
Output: complete Python program

Example

Here __init__() receives the starting values as the object is created:

Prompt
Create a Person class with init() that takes name and age, create an object and print both.
Output: complete Python program

Default Values in __init__()

Parameters of __init__() can also have default values:

Example

Give the age parameter a default value:

Prompt
Create a Person class with init() where age has a default value of 18, create two objects and print their properties.
Output: complete Python program

Multiple Parameters

Give __init__() as many parameters as your class requires:

Example

A Person class that takes several parameters:

Prompt
Create a Person class with init() that takes name, age, city, and country parameters, create an object and print all properties.
Output: complete Python program