__call__ Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。 换句话说,我们可以把这个类型的对象当作函数来使用,相当于 重载了括号运算符。
class Person(object): def __init__(self): pass def __call__(self, *args, **kwargs): print("test") def test1(self,a,b): return a+b def test2(self,a,b): return a*b if __name__=='__main__': p=Person() print(p.test1(2,3)) print(p.test2(3,4))
|