python 有一组内置(built-in)方法,__call__
就是其中一种。__call__
方法使python类的实例化对象可以像函数一样被调用。
具体而言,当一个类定义了__call__
方法,则它的实例化对象作为函数调用时:x(arg1, arg2, ...)
等价于x.__call__(arg1, arg2, ...)
.
例子一
class Example:
def __init__(self):
print("Instance Created")
# 定义__call__方法
def __call__(self):
print("Instance is called via special method")
# 实例化一个 Example 类的对象 e
e = Example()
# 输出:Instance Created
# __call__方法将被对象 e 调用
e()
# 输出:Instance is called via special method
例子二
class Product:
def __init__(self):
print("Instance Created")
# Defining __call__ method
def __call__(self, a, b):
print(a * b)
# Instance created
ans = Product()
# output: Instance Created
# __call__ method will be called
ans(10, 20)
# output: 200