简体   繁体   中英

__init__ or __call__?

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.

Eg: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM