函数字典的语法?

JFA*_*JFA 3 python dictionary

我正在尝试测试使用字典来调用函数的概念,因为python没有a case switch,我不想写出大量的if语句.但是,每当我尝试将函数放入dict时,我都会得到以下结果:

def hello():
...    print 'hello world'
... 
>>> fundict = {'hello':hello()}
hello world
>>> fundict
{'hello': None}
>>> fundict = {'hello':hello}
>>> fundict['hello']
<function hello at 0x7fa539a87578>
Run Code Online (Sandbox Code Playgroud)

如何调用fundict以便hello()在调用时运行?我查看了其他一些堆栈问题,但是我没有理解语法,或者可能没有理解它正在做什么,它给了我一个地址.

Mar*_*ers 7

您调用返回的对象:

fundict['hello']()
Run Code Online (Sandbox Code Playgroud)

您正确存储功能对象; 存储的内容只是一个引用,就像原始名称hello是对函数的引用一样.只需通过添加()(如果函数接受参数,使用参数)调用引用.

演示:

>>> def hello(name='world'):
...     print 'hello', name
... 
>>> hello
<function hello at 0x10980a320>
>>> fundict = {'hello': hello}
>>> fundict['hello']
<function hello at 0x10980a320>
>>> fundict['hello']()
hello world
>>> fundict['hello']('JFA')
hello JFA
Run Code Online (Sandbox Code Playgroud)