Certified Python Developer Learning Resources Object Methods and the init method

Learning Resources

Object Methods and the init method

Object Methods

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
class Person:
    def sayHi(self):
        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.

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 underscores both at the beginning and at the end of the name.


# 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')
# This short example can also be written as Person('Swaroop').sayHi()


   $ 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 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.

 For Support