Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__init__ or __call__?

Tags:

python

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.

like image 949
JeremyL Avatar asked Dec 31 '12 16:12

JeremyL


2 Answers

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__()
like image 104
Gareth Latty Avatar answered Sep 24 '22 20:09

Gareth Latty


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

like image 26
Eric Avatar answered Sep 26 '22 20:09

Eric