[英]Python - Passing a function with multiple arguments into another function
I have this method that I want to pass into another function.我有这个方法,我想传递给另一个 function。
def get_service_enums(context, enum):
svc = Service(context)
return svc.get_enum(enum)
I want to pass this function is as a parameter to another class.我想将这个 function 作为参数传递给另一个 class。
ColumnDef(enum_values=my_func)
Ideally, my_func
is get_service_enums
.理想情况下,
my_func
是get_service_enums
。 However get_service_enums
has a second parameter, enum
that I want to pass in at same time I pass in get_service_enums
.但是
get_service_enums
有第二个参数,我想在传入get_service_enums
的同时传入的enum
。 How can I do this without actually invoking get_service_enums
with parenthesis?如何在不实际调用带括号的
get_service_enums
的情况下执行此操作?
using partial
from functools to create a new function that only takes the first argument.使用 functools 中的
partial
创建一个新的 function,它只接受第一个参数。
from functools import partial
def get_service_enums(context, enum):
print(context, enum)
partial_function = partial(get_service_enums, enum="second_thing")
partial_function("first_thing")
first_thing second_thing
Does it not work for you to pass the function and its argument separately单独传递 function 及其参数对您不起作用吗
ColumnDef(enum_values=get_service_enums, enum)
with the class ColumnDef
in charge of passing in enum
when the function is invoked?使用 class
ColumnDef
负责在调用 function 时传入enum
?
If not, functools.partial
is your friend:如果不是,
functools.partial
是你的朋友:
import functools
# New version of get_service_enums with enum = 42
my_func = functools.partial(get_service_enums, enum=42)
my_func('hello') # hello, 42
ColumnDef(enum_values=my_func)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.