We have already discussed that classes/objects can have methods which are just like functions except for the usage of the self variable. Even if your method does not take any parameters, you still have to have the self variable.
Example 11.2. Using Object Methods
#!/usr/bin/python # Filename: methods.py class Person: def sayHi(self): print 'Hello, how are you?' p = Person() p.sayHi() # This short example can also be written as Person().sayHi()
Here we see the self variable in action. Notice, that the sayHi method takes no parameters but still has the self variable in it's parameter list in the function definition. Other than this, methods are no different from functions.
You can define a special method for a class with the name __init__ which is run as soon as an object of this class is instantiated. This method is used for any initialization you want to do with your object. The next example will demonstrate this.
The __init__ method is analogous to a constructor in C++ or C# or Java.