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:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 36)
print(p1.name)
print(p1.age)
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__():
Output: complete Python program
class Person:
pass
p1 = Person()
p1.name = "Tobias"
p1.age = 25
print(p1.name)
print(p1.age)
Example
Here __init__() receives the starting values as the object is created:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Linus", 28)
print(p1.name)
print(p1.age)
Default Values in __init__()
Parameters of __init__() can also have default values:
Example
Give the age parameter a default value:
Output: complete Python program
class Person:
def __init__(self, name, age=18):
self.name = name
self.age = age
p1 = Person("Emil")
p2 = Person("Tobias", 25)
print(p1.name, p1.age)
print(p2.name, p2.age)
Multiple Parameters
Give __init__() as many parameters as your class requires:
Example
A Person class that takes several parameters:
Output: complete Python program
class Person:
def __init__(self, name, age, city, country):
self.name = name
self.age = age
self.city = city
self.country = country
p1 = Person("Linus", 30, "Oslo", "Norway")
print(p1.name)
print(p1.age)
print(p1.city)
print(p1.country)