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