函数curring的目的是方便地从更一般的函数中获取专门的函数。您可以通过在不同的时间预先设置一些参数并在之后保持这些参数不变来实现这一目的。
这与命名无关。在Python中,您可以随时轻松地重命名变量/函数。
示例:def simple_function(a):
def line(b=0):
def compute(x):
return [a+b * xi for xi in x]
return compute
return line
x = range(-4, 4, 1)
print('x {}'.format(list(x)))
print('constant {}'.format(simple_function(3)()(x)))
print('line {}'.format(simple_function(3)(-2)(x)))
给予x [-4, -3, -2, -1, 0, 1, 2, 3]
constant [3, 3, 3, 3, 3, 3, 3, 3]
line [11, 9, 7, 5, 3, 1, -1, -3]
现在还没有那么激动人心。它只将类型为f(a,b,c)的函数调用替换为类型为f(a)(b)(c)的调用,这甚至可能被视为Python中不太优雅的风格。
但它允许你做:line_through_zero = simple_function(0)
print('line through zero {}'.format(line_through_zero(1)(x))) # only slope and x
它给予line through zero [-4, -3, -2, -1, 0, 1, 2, 3]
因此,curring的优点是,您可以获得具有固定参数的专用函数,并且可以使用这些函数,而不是编写更通用的表单并在每次调用时设置固定的参数。
咖喱的替代品是:partial,lambda和default parameters。因此,在实践中,咖喱可能是有用的,但你也可以绕过它,如果你想。