作用:使得“对象”具备当作函数,来调用的能力
1、类没有__call__()方法:
class Person:
pass
p = Person()
p()
此时报错,p这个对象没办法当作函数使用,报错如下:
Traceback (most recent call last):
File “/home/xxx/test.py”, line 5, in
p()
TypeError: ‘Person’ object is not callable
2、类添加__call__()方法:
class Person:
def __call__(self, *args, **kwargs):
print("xxx")
print(args)
print(kwargs)
pass
p = Person()
p(123, 456, name='zhangsan')
运行结果:
xxx
(123, 456)
{‘name’: ‘zhangsan’}
参考文献: