函数只是一个可以调用的对象,因此使用__call__ 方法定义类原则上等同于定义函数。至少在你提供的上下文中。
所以:
def user_func(x, y, z):
return anything_with(x, y, z)
相当于:
class user_class(object):
@staticmethod # staticmethod so that it can be called on the class
def __call__(x, y, z):
return anything_with(x, y, z)
就目前而言,这只是混淆。但是,当您创建一个具有预定义属性的实例并且您只将变量参数指定为call 的参数时,奇迹就会发生:
class user_class(object):
def __init__(self, x):
self.x = x
def __call__(self, y, z): # No x as parameter!
return do_anything_with(self.x, y, z) # use the predefined x here
但是你需要改变你调用lib_func的方式然后:
x = 0
user_class_instance = user_class(0)
result = lib_func(user_class_instance, param1)
因此它将重复调用具有不同 y 和 z 的实例,但 x 将保持不变
大多数这样的lib_func 函数都允许传递可变参数(这些参数将传递给user_func),例如scipy.optimize.curve_fit:
curve_fit(user_func, x, y, [initial_guess_param1, param2, ...])
user_func 将在内部被 curve_fit 调用(您无需执行任何操作!)例如:
user_func(x, initial_guess_param1, param2, ...)
# Then curve-fit modifies initial_guess_param1, param2, ... and calls it again
user_func(x, initial_guess_param1, param2, ...)
# and again modifies these and calls again
user_func(x, initial_guess_param1, param2, ...)
# ... until it finds a solution
x 和 y 已定义且在调用 curve_fit 时不会更改,但 initial_guess_param1 将在找到最佳 curve_fit 时更改
.