Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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 parametername (along with the usualself). Here, we just create a new field also calledname. 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 theself.name field in our methods which is demonstrated in thesayHi method.

Note for C++/Java/C# Programmers

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