8
votes

When should I use __init__ and when __call__ method ?

I am confused about whether should I use the first or the second.

At the moment I can use them both, but I don't know which is more appropriate.

4
Well, what are you trying to do? - arshajii
You can use them both, and implement them both. If you won't tell us what you are trying to do, how can we help? Did you find the documentation confusing? Which part confused? - David Heffernan

4 Answers

19
votes

These two are completely different.

__init__() is the constructor, it is run on new instances of the object.

__call__() is run when you try to call an instance of an object as if it were a function.

E.g: Say we have a class, Test:

a = Test() #This will call Test.__init__() (among other things)
a() #This will call Test.__call__()
9
votes

A quick test shows the difference between them

class Foo(object):
    def __init__(self):
        print "init"
    def __call__(self):
        print "call"

f = Foo()  # prints "init"
f()        # prints "call"

In no way are these interchangeable

7
votes

Most likely, you want to use __init__. This is the method used to initialize a new instance of your class, which you make by calling the class. __call__ is in case you want to make your instances callable. That's not something frequently done, though it can be useful. This example should illustrate:

>>> class C(object):
...   def __init__(self):
...     print 'init'
...   def __call__(self):
...     print 'call'
... 
>>> c = C()
init
>>> c()
call
>>> 
2
votes

A simple code snippet will elaborate this better.

>>> class Math:
...     def __init__(self):
...             self.x,self.y=20,30
...     def __call__(self):
...             return self.x+self.y
... 
>>> m=Math()
>>> m()
50