您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中使用字典调用带有参数的函数

在Python中使用字典调用带有参数的函数

functools.partial创建字典时,我将使用此参数来指定参数:

from functools import partial

options = {0: FunctionZero,   
           1: FunctionOne,    
           2: FunctionTwo,
           3: partial(FunctionThree, True)}

请注意,这还允许在调用函数时传递其他参数(只要字典中的所有函数partial调用后都缺少相同的参数):

def test(one, two, three=None, four=None):
    ...

def test2(one, two, three=None):
    ...

options = {1: partial(test, 1, three=3, four=4),
           2: partial(test2, 1, three=3)}

...

options[choice](2) # pass the 'two' argument both functions still require
python 2022/1/1 18:38:52 有267人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶