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__
?
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, ...) .
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.
__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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With