gpt4 book ai didi

python - 如何将多个函数存储为字典的值?

转载 作者:行者123 更新时间:2023-11-28 17:09:11 25 4
gpt4 key购买 nike

在下面的代码中,我尝试将多个函数存储为字典的值。此代码不起作用。这两个函数作为元组返回。但我不想翻阅字典。我想用一个特殊的键,然后我想让字典运行这两个函数。

from functools import partial

def test_1(arg_1 = None):
print "printing from test_1 func with text:", arg_1

def test_2(arg_2 = None):
print "printing from test_2 func with text:", arg_2

dic = {'a':(partial(test_1, arg_1 = 'test_1'),
partial(test_2, arg_2 = 'test_2'))}

dic['a']()

最佳答案

您可以构建一个闭包来执行此操作,例如:

代码:

def chain_funcs(*funcs):
"""return a callable to call multiple functions"""
def call_funcs(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)

return call_funcs

测试代码:

def test_1(arg_1=None):
print("printing from test_1 func with text: %s" % arg_1)


def test_2(arg_2=None):
print("printing from test_2 func with text: %s" % arg_2)


from functools import partial
dic = {'a': chain_funcs(partial(test_1, arg_1='test_1'),
partial(test_2, arg_2='test_2'))}

dic['a']()

结果:

printing from test_1 func with text: test_1
printing from test_2 func with text: test_2

关于python - 如何将多个函数存储为字典的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com