Your shopping cart is empty!
We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable. We will now see an example.
# Filename: method.py
print('Hello, how are you?')
p = Person()
# This short example can also be written as Person().sayHi()
$ python method.py
Hello, how are you?
How It Works:
Here we see the self in action. Notice that the sayHi method takes no parameters but still has the self in the function definition.
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 underscores both at the beginning and at the end of the name.
# Filename: class_init.py
def __init__(self, name):
self.name = name
print('Hello, my name is', self.name)
p = Person('Swaroop')
# This short example can also be written as Person('Swaroop').sayHi()
$ python class_init.py
Hello, my name is Swaroop
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 are both called 'name'. There is no problem because the dotted notation self.name means that there is something called "name" that is part of the object called "self" and the other name is a local variable. Since we explicitly indicate which name we are referring to, there is no confusion.
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.