Take the 2-minute tour ×

I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.

What I'm trying to figure out is:

In a method:

def method(self, blah):
    def __init__(?):

What does self do? what is it meant to be? and is it mandatory?

What does the __init__ method do? why is it necessary? etc

I think they might be oop constructs, but I don't know very much..

share|improve this question
Your sample code looks all messed up. Luckily many answers contain proper Python class examples, hopefully setting you straight. :) –  unwind Mar 9 '09 at 10:48
diveintopython.net/object_oriented_framework/… see here on the function of the __init__ method. Especially 5.3.1 example 5.5 –  franklin Jul 6 '13 at 18:18
possible duplicate of What is the purpose of self in Python? –  Antti Haapala Feb 20 at 11:11
possible duplicate of Why do we use __init__ in python classes? –  PM 2Ring Feb 20 at 11:32

12 Answers 12

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__ method
a.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.

share|improve this answer
what if you put x = 'Hello' outside init but inside the class? is it like java where it's the same, or does it become like a static variable which is only initialised once? –  Jayen Apr 9 '12 at 0:41
It's like a static variable. It's only initialized once, and it's available through A.x or a.x. Note that overriding it on a specific class will not affect the base, so A.x = 'foo'; a.x = 'bar'; print a.x; print A.x will print bar then foo –  Chris B. Apr 9 '12 at 15:46
It's worth pointing out that the first argument need not necessarily be called self, it just is by convention. –  Henry Gomersall Jun 24 '12 at 19:37

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 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).

share|improve this answer
So, that means if we do not wish to initialize any class variables, we can just forget __init__(self): Am I correct? –  Tharindu Rusira Jul 16 '13 at 8:34
@TharinduRusira Yep –  RedBlueThing Jul 16 '13 at 8:57
why you have used underscores? –  avi Nov 21 '13 at 9:27
Underscores are used to indicate those class members are "private". Client code should not depend on them. They may change in the future. It's just a convention. –  Wei Qiu Nov 22 '13 at 12:53
@TharinduRusira no. They are instance variables, not class variables –  Antti Haapala Feb 19 at 10:15

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
share|improve this answer
Interesting observation but I think you are on the wrong track. With print MyClass.i it looks more like you are calling a 'static' variablie i. Where as with a.i you are calling a member variable, i. It seems to me that init is just a constructor that is first executed when you create an object of the class. –  captainspi Jun 23 '13 at 17:38
That's what I was trying to 'explain to myself' with this example - that the variable set by __init__ is what gets passed to instances of the class, not the 'static' variable of the class itself that has the same name... –  Dave Everitt Jun 25 '13 at 8:34

In short:

  1. self as it suggests, refers to itself- the object which has called the method. That is, if you have N objects calling the method, then self.a will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a for each object
  2. __init__ is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created

HTH, Amit

share|improve this answer

They are OOP constructs. If you are a beginner in OOP, it's going to be hard to explain them in a few sentences.

Here's a tutorial that introduces OOP in Python. It also provides some answers to your questions:


share|improve this answer
This answer basically says "I am not attempting to answer this question but have a link", unbelievable that it got the number of upvotes it got. –  Antti Haapala Feb 19 at 13:06

__init__ does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods. "self" are instance variables for your class.

share|improve this answer

Basically, you need to use the 'self' keyword when using a variable in multiple functions within the same class. As for init, it's used to setup default values incase no other functions from within that class are called.

share|improve this answer
There is no 'self' keyword in Python. Calling the first parameter 'self' is simply a convention. –  Dave76 Nov 13 '14 at 22:21

The 'self' is a reference to the class instance

class foo:
    def bar(self):
            print "hi"

Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:

f = foo()

But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing

f = foo()

Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language

class foo:
    def bar(s):
            print "hi"
share|improve this answer
Why does that say anything about the flexible nature of the language? It just says you can give variables any legal name you choose. How is that different from any other programming language? –  Daniel Sep 11 '14 at 21:44
As I wrote in my answer "bar" is just a function where a class instance is provided as the first parameter. So while "bar" is defined as a method bound to "foo" it could also be called with an instance of some other class. This is not how methods and "this" work in Java for example, although I imagine you see that these are the same concept, functions and some instance context (the instance context being the first parameter in Python and "this" in Java"). Perhaps you can now see the flexibility of the language I was referring to? –  tarn Oct 16 '14 at 13:59
Yeah that does show the flexibility of the language. The way you phrased your answer, it seemed like you were saying that the fact that you could call the "self" variable something else (like s) was showing the flexibility of python. –  Daniel Oct 19 '14 at 1:30

note that self could actually be any valid python identifier. For example, we could just as easily write, from Chris B's example:

class A(object):
    def __init__(foo):
        foo.x = 'Hello'

    def method_a(bar, foo):
        print bar.x + ' ' + foo

and it would work exactly the same. It is however recommended to use self because other pythoners will recognize it more easily.

share|improve this answer

Had trouble undestanding this myself. Even after reading the answers here.

To properly understand the __init__ method you need to understand self.

The self Parameter

The arguments accepted by the __init__ method are :

def __init__(self, arg1, arg2):

But we only actually pass it two arguments :

instance = OurClass('arg1', 'arg2')

Where has the extra argument come from ?

When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.

In order to access object attributes from within the __init__ method we need a reference to the object.

Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.

This means in the __init__ method we can do :

self.arg1 = arg1
self.arg2 = arg2

Here we are setting attributes on the object. You can verify this by doing the following :

instance = OurClass('arg1', 'arg2')
print instance.arg1

values like this are known as object attributes. Here the __init__ method sets the arg1 and arg2 attributes of the instance.

source: http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method

share|improve this answer

You would be correct, they are object-oriented constructs. Basically self is a reference (kind of like a pointer, but self is a special reference which you can't assign to) to an object, and __init__ is a function which is called to initialize the object - that is, set the values of variables etc. - just after memory is allocated for it.

share|improve this answer

Try out this code. Hope it helps many C programmers like me to Learn Py.

#! /usr/bin/python

class Person:

    '''Doc - Inside Class '''

    def __init__(self, name):
        '''Doc - __init__ Constructor'''
        self.n_name = name        

    def show(self, n1, n2):
        '''Doc - Inside Show'''
        print self.n_name
        print 'Sum = ', (n1 + n2)

    def __del__(self):
        print 'deleting object Destructor', self.n_name

p.show(2, 3)
print p.__doc__
print p.__init__.__doc__
print p.show.__doc__
share|improve this answer

Your Answer

