Thursday, 17 December 2009

What does __init_ and self do?

class Point:
def __init__(self, x, y):
self._x = x
self._y = y

The init method gets called when memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the init method like this:

class Point:
def __init__(self, x, y):
_x = x
_y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x sets those variables as members of the Point object (accessible for the lifetime of the object).

No comments:

Post a Comment

Tweets by @sriramperumalla