NEXT TUTORIAL >> Nested Class in Python
The __init__() method in Python is a default method that is mainly used to initialize the instance variables of a class. For the same reason, it is also referred to as Constructor.
The first parameter of the __init__() method is the self variable containing the memory address of the instance.
Here is the complete tutorial that we have designed for self statement : http://codeofgeeks.com/the-self-variable-in-python-class/
Sample __init__() method is defined as :
def __init__(self):
self.name = 'Ram'
self.role = 'God'
In the above code, the constructor __init()__ has only one parameter i.e self. With the help of self.name and self.role, we can access the instance variables of the class.
The __init__() method is called automatically at the time of instance creation. Like,
a = Animal() # Here Animal is our class
Observe the empty parentheses while instantiating a class, this means that we are not passing any values to the constructor at the time of class instantiation.
Let’s try to add some parameters to it now,
a = Animal('meows', 'barks') # Here Animal is our class
The __init__() method to accept the values,
def __init__(self, cat = 'speaks hindi', dog = 'speaks english'):
self.cat = cat
self.dog = dog
In this case, we are passing two actual arguments, ‘meows’ and ‘barks’ to the Animal class.
Let’s see the whole code to understand the flow,
class Animal:
def __init__(self, cat = 'speaks hindi', dog = 'speaks english'):
self.cat = cat
self.dog = dog
def display(self):
print(self.cat)
print(self.dog)
a1 = Animal('meows', 'barks') # calling with parameters
a1.display()
a2 = Animal() # calling without parameters
a2.display()
Please note that, even if you don’t write __init__() method inside your class, then too, default constructor will be executed.
class Animal:
def display(self):
print('No init here @@')
a2 = Animal() # calling without parameters
a2.display()
O/P
No init here @@
Why __init__() method has two trailing and leading underscores ?
Python calls it a special method. This is just a convention, a way for the Python system to use names that won’t conflict with user-defined names. Other examples are __file__, __import__.
That’s all here. Hope, you now know the significance of __init__() method.
NEXT TUTORIAL >> Nested Class in Python
