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:
[pastacode lang=”markdown” manual=”class%20my_class(object)%3A%0A%20%20def%20__init(self%2C%20x%2C%20y)%3A%0A%20%20%20%20self.x%20%3D%20x%0A%20%20%20%20self.y%20%3D%20y%0Adef%20f2(self)%3A%0A%20%20%20%20return%20self.x%20%2B%20self.y%0A%20a%20%3D%20my_class(10%2C%2020)%0Aprint%20a.f2()” message=”” highlight=”” provider=”manual”/]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.
