Product SiteDocumentation Site

11.2. __init__ method

__init__ is a special method in python classes, it is the constructor method for a class. In the following example you can see how to use it

>>> class Student:
...   def __init__(self, name, branch, year):
...     self.name = name
...     self.branch = branch
...     self.year = year
...     print "A student object is created"
...   def getName(self):
...     return self.name
...   def setName(self, name):
...     self.name = name
...

__init__ is called when ever an object of the class is constructed.That means when ever we will create a student object we will see the message "Creating a new student" in the prompt. You can see the first argument to the method is self. It is a special variable which points to the current object (like `this` in C++). The object is passed implicitly to every method available in it , but we have to get it explicitly in every method while writing the methods. Example shown below.

>>> std1 = Student()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (1 given)
>>> std1 = Student('Kushal','CSE','2005')
A student object is created

In this example at first we tried to create a Student object with passing any argument and python interpreter complained that it takes exactly 4 arguments but received only one (self). Then we created an object with proper argument values and from the message printed, one can easily understand that __init__ method was called as the constructor method.
Now we are going to call getName() and setName() methods.

>>> std1.getName()
'Kushal'
>>> std1.setName()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: setName() takes exactly 2 arguments (1 given)
>>> std1.setName('Shreyank Gupta')
>>> std1.getName()
'Shreyank Gupta'

First we called getName on the object we created, then tried to call setName without any arguments and we got an error. Next we again called setName with argument 'Shreyank Gupta'. Now calling getName gives 'Shreyank Gupta' as the output.