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(object):
    """
    Returns a ```Student``` object with the given name, branch and year. 
    
    """
    def __init__(self, name, branch, year):
            self.name = name
            self.branch = branch
            self.year = year
            print "A student object is created"

    def set_name(self, name):
        """
        Sets the name of the student.

        :arg name: new name ofthe student.
        
        """
        self.name = name

    def get_name(self):
        """
        Returns the name of the student.
        
        :return: a string contain the student's name

        """
        return self.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.get_name()
'Kushal'
>>> std1.set_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set_name() takes exactly 2 arguments (1 given)
>>> std1.set_name('Shreyank Gupta')
>>> std1.get_name()
'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.