简体   繁体   中英

When should I implement __call__

In python you can make instances callable by implementing the __call__ method. For example

class Blah:
    def __call__(self):
        print "hello"

obj = Blah()
obj()

But I can also implement a method of my own, say 'run':

class Blah:
    def run(self):
        print "hello"

obj = Blah()
obj.run()

When should I implement __call__ ?

This is hard to answer. My opinion is that you should never define __call__ unless your actual goal is to create a function. It's not something you would do after you've already created a traditional object.

In other words, if you're starting out thinking "I'm going to create an object" you should never end up implementing __call__ . If, on the other hand, you start out thinking "I'm going to create a function... but I wish I could use the object framework to let my function have some state" then you could create the function as an object with state, and define __call__ to make it act like a function.

I want to include one final bit of advice which was provided by @Paul Manta in a comment to the question, where he wrote:

If you're unsure if you need __call__ , then you don't need __call__

I think that's sound advice.

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