我试图测试使用字典调用函数的概念,因为python没有case switch
而且我不想写出大量的{{ 1}}语句。但是,每当我尝试将函数放入dict时,我都会得到以下结果:
if
如何调用def hello():
... print 'hello world'
...
>>> fundict = {'hello':hello()}
hello world
>>> fundict
{'hello': None}
>>> fundict = {'hello':hello}
>>> fundict['hello']
<function hello at 0x7fa539a87578>
,以便在调用时运行fundict
?我查看了其他一些堆栈问题,但我没有理解语法,或者可能没有理解它正在做什么,它给了我一个地址。
答案 0 :(得分:7)
您调用返回的对象:
fundict['hello']()
您正确存储功能对象;存储的内容只是一个引用,就像原始名称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
答案 1 :(得分:1)
Python中的所有对象都是一流的(阅读great article by Guido)。这基本上意味着您可以将它们分配给变量,比较它们,将它们作为参数传递等。例如:
class C(object):
pass
class_c = C
# they are the same
assert class_c is C
# they are both instance of C
instance1 = class_c()
instance2 = C()
def f():
pass
function_f = f
# again, they are the same
assert function_f is function
# both results are results from function f
result1 = f()
result2 = function_f()
这同样适用于实例方法(绑定和未绑定),静态方法和类方法。因为您可以将它们视为变量,您可以将它们放入字典中:
fundict = {'hello' : hello}
后来使用它们:
function = fundict['hello']
function()
# or less readable:
fundict['hello']()
您所拥有的奇怪输出与您在原始hello
中看到的相同:
>>> fundict['hello']
<function hello at 0x7fa539a87578>
>>> hello
<function hello at 0x7fa539a87578>