There are several special method_names in Python with special significance among classes defined. We shall discuss one of the most commonly used __init__ method below:
__init__ method is executed as soon as an object of a class is initiated. The method is used to do any initialization of variables. The syntax of defining this method is to use two underscores before and two underscores after the init method name.
__init__ function in a class is executed even if that part of the function is not called in the class. This can be best explained by the example,
def __init__ (self): # function 1, executed even if its not called when ever the class is triggered.
def hardwork(self): # function 2, executed only when the function in the class is triggered.
print(' hardwork always pays ')
hello = placements() # object created.
hardwork always pays # it needs to be observed that only hardwork() function was called in the placements() class but __init__ function automatically was executed without calling.
In the previous article we had discussed about backend development of a computer game. Now, let us implement similar program with __init__ function in it to understand the best use of this function:
self.energy = x
def get_energy (self):
Jhon = Enemy(5) # the value of x is passed as a parameter
Sandy = Enemy (18) # big enemy of large health