Python中字典中的求值函数

2024-04-24 05:19:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本包含函数的字典。例如:

def myfunction(parameter) = return "Function with parameter " % parameter
dictionary = {"myfunction" : myfunction}

现在我想用参数调用这个函数,例如,如果输入如下所示:

^{pr2}$

第一个单词是字典的键,其他单词是此函数的参数(或包含字符串的一个参数)。在

是否可以使用eval()?如何将参数传递给函数?在

谢谢你的建议。在


Tags: 函数字符串参数dictionaryreturn字典parameterdef
2条回答

下面是一个通用示例:

>>> def hello(name='World'): print('Hello %s' % name)

>>> hello()
Hello World

>>> hello('Vist')
Hello Vist

>>> d = {'fun': hello}

>>> d['fun']()
Hello World

>>> d['fun']('Vist')
Hello Vist

参数数目可变的示例:

^{pr2}$

我将拆分您的输入字符串,并使用第一个块在字典中查找函数。然后将剩余的块传递给函数。在

s = 'myfunction some string'
chunks = s.split()

func = dictionary.get(chunks[0])

if not func:
    print 'Not found'
    return

func(chunks[1:])

相关问题 更多 >