[英]How to call Python partial without using parentheses?
Suppose the code below: 假设下面的代码:
from functools import partial
import random
def integer(min=1, max=10):
return random.randint(min, max)
def double(min=1, max=10):
return random.uniform(min, max)
if __name__ == '__main__':
p1 = partial(integer, 5, 10)
p2 = partial(double, 5, 10)
for f in [p1, p2]:
f() # I'd like to know if there's a different way to call this like `call(f)` or something
As mentioned in the comment, I'd like to know if there's a way to call f
without using parentheses. 如评论中所述,我想知道是否可以在不使用括号的情况下调用f
。 One step further, suppose I can call f
without using parentheses, if I would like to pass additional parameters to f
, how do I go about it (like call(f, additional_param_1, additional_param_2)
)? 更进一步,假设我可以不使用括号就调用f
,如果我想将附加参数传递给f
,我该如何处理(例如call(f, additional_param_1, additional_param_2)
)?
Thank you in advance for your answers! 预先感谢您的回答!
Not in base Python, but you can easily write call()
yourself: 不是在基本的Python中,但是您可以自己编写call()
:
from functools import partial
import random
def integer(min=1, max=10):
return random.randint(min, max)
def double(min=1, max=10):
return random.uniform(min, max)
def call(f, *args, **kwargs):
return f(*args, **kwargs)
if __name__ == '__main__':
p1 = partial(integer, 5, 10)
p2 = partial(double, 5, 10)
for f in [p1, p2]:
call(f)
Note: you have a typo in your example, you're calling partial
on int
, but your function is called integer
. 注意:您的示例中有一个错字,您在int
上调用了partial
,但是您的函数称为integer
。 (neither is a very good name and I think you're trying to solve a problem that you're not stating, that has a better solution) (都不是一个很好的名字,我认为您正在尝试解决一个您没有说明的问题,这是一个更好的解决方案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.