[英]python function with arguments assigned to a variable
I have a function 我有一个功能
def x(whatever):
....
I want to assign 我要分配
y = x(whatever)
So that I can pass around y to a wrapper which then calls the method that y refers to. 这样我就可以将y传递给包装器,然后包装器调用y所引用的方法。 The problem is that each type of function x can have variable arguments.
问题在于函数x的每种类型都可以具有变量参数。 Is it possible to do this in python, assigning y = x(whatever) and then pass around y as a parameter.
是否有可能在python中执行此操作,分配y = x(无论如何),然后将y作为参数传递。
I tried y = x(whatever) and passed around y to the wrapper which then did 我尝试y = x(无论如何)并将y传递给包装器,然后包装器
ret = y() # dict object is not callable
Thanks! 谢谢!
I think you are looking for functools.partial()
: 我认为您正在寻找
functools.partial()
:
from functools import partial
y = partial(x, whatever)
When y
is called, x(whatever)
is called. 调用
y
将调用x(whatever)
。
You can achieve the same with a lambda
: 您可以使用
lambda
实现相同的目的:
y = lambda: x(whatever)
but a partial()
accepts additional arguments, which will be passed on to the wrapped callable. 但是
partial()
接受其他参数,这些参数将传递给包装的可调用对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.