init function in Python

05 min read

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:

The  __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,

class placements:

     def __init__ (self): # function 1, executed even if its not called when ever the class is triggered.

                     print("FACE Prep")

      def hardwork(self): # function 2, executed only when the function in the class is triggered.

                    print(' hardwork always pays ')

hello = placements()        # object created.

hello.hardwork() 

Output:

FACE Prep
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:

class enemy:

         def __init__(self,x):

                    self.energy = x

       def get_energy (self):

                print(self.energy)

Jhon   = Enemy(5)         # the value of x is passed as a parameter

Sandy = Enemy (18)     # big enemy of large health

Jhon.get_energy()

Sandy.get_energy()

 

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error