Python init():

  • In Python, __init__() method within a class is its constructor.Any method or variable that starts with double underscore is by default private.
  • Python defines several standard private methods that have a special meaning, and __init__() is one of them. Some others are __str__(), __repr__(), __add__() and others.

What does def init do in Python ?

  • The __init__ function is known as a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the recently created object is assigned to the parameter “self”. The notation self.legs is an attribute called legs of the object in the variable self.

Sample Code:

class my_class(object):
def __init(self, x, y):
self.x = x
self.y = y
def f2(self):
return self.x + self.y
a = my_class(10, 20)
print a.f2()

Output :

30 

In the constructor __init__() and method f2(), a initial parameter self is a reference to a object that will later invoke methods at run time. Actually leaving out self parameter in the definition makes it not possible to call it on behalf of the object.

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,