What __init__ and self do in Python? What __init__ and self do in Python? python python

What __init__ and self do in Python?


In this code:

class A(object):    def __init__(self):        self.x = 'Hello'    def method_a(self, foo):        print self.x + ' ' + foo

... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in ...

a = A()               # We do not pass any argument to the __init__ methoda.method_a('Sailor!') # We only pass a single argument

The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.


Yep, you are right, these are oop constructs.

__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

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

The __init__ method gets called after 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 and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).

N.B. Some clarification of the use of the word "constructor" in this answer. Technically the responsibilities of a "constructor" are split over two methods in Python. Those methods are __new__ (responsible for allocating memory) and __init__ (as discussed here, responsible for initialising the newly created instance).


A brief illustrative example

In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__ function:

class MyClass(object):    i = 123    def __init__(self):        self.i = 345     a = MyClass()print(a.i)print(MyClass.i)

Output:

345123