我有一个函数,我正在尝试制作它的部分版本,然后在 reduce 语句中应用该部分函数。
偏函数本身是有效的——因为我可以正常地用一组参数调用它,它会返回正确的答案。但是,如果在 reduce 下应用它会中断
例如;
import functools
test=[1,2,3,4]
def base_function(mult=10,a=0,b=0):
return(mult*(a+b))
#control function, should act like partial base_function with mult=1
def test_function1(a=0,b=0):
return(a+b)
#stupid partial function that has destroyed my friday afternoon
test_function2=functools.partial(base_function,mult=1)
print(test_function2.args) #returns ()
print(test_function2.keywords) #returns {'mult':1}
print(test_function1(a=1,b=2)) #returns 3 as expected
print(test_function2(a=1,b=2)) #returns 3 as expected! horray!
#so the partial function itself works when called normally
print(functools.reduce(test_function1,test,-20)) #returns -10
print(functools.reduce(test_function2,test,-20)) #returns TypeError: base_function() got multiple values for argument 'mult'
作为额外的奖励,如果我更改代码使 mult 成为位置参数并更新偏函数;
def base_function(mult,a=0,b=0):
return(mult*(a+b))
def test_function1(a=0,b=0):
return(a+b)
test_function2=functools.partial(base_function,1)
print(test_function2.args)
print(test_function2.keywords)
这该死的东西在 reduce 语句中工作得很好。
谁能给我解释一下?对于这种类型的错误,我能找到的唯一答案似乎适用于有人将函数中的某个东西同时作为关键字和普通参数调用的情况——据我所知,这并没有发生在这里——如果是这样的话部分函数在正常调用时不应该正常工作。使 mult 成为位置参数的“解决方案”是可行的,但我真的很想知道是什么导致了这个错误,因为显然我一定是误解了一些重要的东西。
编辑:感谢回答我问题的发帖者 - 我现在明白为什么会发生这种情况以及为什么重新排列参数或使它们定位可以解决问题,所以我将其标记为已解决。
不过,我确实想知道是否有一种“简洁”的方式来做到这一点——一个类似部分的运算符,如果参数被正确传递,它不仅返回一个部分对象,该对象的行为类似于所需的函数,而且从字面上返回一个任意的所需的无需预定义任意函数的函数。例如:
import functools
def base_function(mult=10,a=0,b=0):
return(mult*(a+b))
def test_function1(a=0,b=0):
return(a+b)
test_function2=partial_like_operator(base_function,mult=1)
print(test_function2==test_function1) #prints true
请您参考如下方法:
@horoy 是对的。
另一种解释方式:
在幕后,对 reduce 的调用给出了一个错误,最终调用如下:
test_function2(x, y, mult=1)
其中 x 和 y 是 reduce 函数的局部变量。
您可以尝试一下,自己很容易看出这不是一个有效的调用。传递的第一个参数必须对应于 mult,因为这是函数的第一个参数,但是 mult 会传递另一个值,作为 kw arg。
在调用有效的部分函数的测试中,您将 a 和 b 作为 kwargs 传递,从而绕过了这个问题。
结论是,当使用 partial 时,最好将其设计为绑定(bind)函数的最后一个参数,而不是第一个。
