Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I implement __call__

Tags:

python

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__?

like image 596
zetafish Avatar asked Apr 23 '12 20:04

zetafish


People also ask

What is the use of __ call __ in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

How do you call the __ str __ method?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is the purpose of the magic method __ init __?

__init__ : "__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.

What does the __ New__ method do?

In the base class object , the __new__ method is defined as a static method which requires to pass a parameter cls . cls represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.


1 Answers

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.

like image 174
Bryan Oakley Avatar answered Sep 20 '22 10:09

Bryan Oakley