A Byte of Python

The __init__ method

There are many method names which have special significance in Python classes. We will see the significance of the __init__ method now.

The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscore both in the beginning and at the end in the name.

Using the __init__ method

Example 11.3. Using the __init__ method

				
#!/usr/bin/python
# Filename: class_init.py

class Person:
	def __init__(self, name):
		self.name = name
	def sayHi(self):
		print 'Hello, my name is', self.name

p = Person('Swaroop')
p.sayHi()

# This short example can also be written as Person('Swaroop').sayHi()
				
				

Output

				
$ python class_init.py
Hello, my name is Swaroop
				
				

How It Works

Here, we define the __init__ method as taking a parameter name (along with the usual self). Here, we just create a new field also called name. Notice these are two different variables even though they have the same name. The dotted notation allows us to differentiate between them.

Most importantly, notice that we do not explicitly call the __init__ method but pass the arguments in the parentheses following the class name when creating a new instance of the class. This is the special significance of this method.

Now, we are able to use the self.name field in our methods which is demonstrated in the sayHi method.

Note for C++/Java/C# Programmers

The __init__ method is analogous to a constructor in C++, C# or Java.