__call__ is a very special instance method in Python classes, which enables class instance objects to be used in the form of "object name()" just like calling ordinary functions.Objects in Python that can be followed by () to call execution are called callable objects.If the __call__() method is defined in the class, then the instance object of the class will also become a callable object.When the object is called, the code in the __call__() method will be executed.
class Entity:def __init__(self, x, y):self.x = xself.y = yprint("Initialize x:{0},y:{1}".format(x, y))def __call__(self, x, y):self.x, self.y = x, yprint("modified x:{0},y:{1}".format(x, y))e = Entity(1, 2) # create instancee(4, 5) # The instance can be executed like a function, passing in the x y value, modifying the x y of the object
Execute the above code, the output result is:
Initialize x:1,y:2Modified x:4,y:5
Instance objects can also be used as callable objects like functions. So, in what scenarios is this feature useful?
This needs to be combined with the characteristics of the class. The class can record data (attributes). Using this feature, you can implement class-based decorators and record the status in the class. For example, in the following example, the function is called.Times: