Brush face questions can see, this method did not understand what practical use, the official document as follows:
3.3.6. Emulating callable objects
-
object.
__call__
(self[, args...]) -
Called when the instance is “called” as a function; if this method is defined,
x(arg1, arg2, ...)
is a shorthand forx.__call__(arg1, arg2, ...)
.
The main achievement is the direct object class as a function call
E.g:
class Demo(object): def __init__(self, a, b): self.a = a self.b = b def my_print(self,): print("a = ", self.a, "b = ", self.b) def __call__(self, *args, **kwargs): self.a = args[0] self.b = args[1] print("call: a = ", self.a, "b = ", self.b) if __name__ == "__main__": demo = Demo(10, 20) demo.my_print() demo(50, 60)
The results are as follows:
a = 10 b = 20
call: a = 50 b = 60
Note that: only when the class is defined def __call __ () method, we can achieve this function, otherwise a syntax error occurs, the document is to explain if this method is defined meaning.