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