用整数作为字典的键,函数作为值?

5
这是我的代码:
def test1():
  print("nr1")

def test2():
  print("nr2")

def test3():
  print("nr3")

def main():
  dictionary = { 1: test1(), 2: test2(), 3: test3() }
  dictionary[2]

if __name__ == "__main__":
  main()

这段代码返回:
nr1
nr2
nr3

我需要修改代码才能得到这个结果:
nr2

我正在使用Python 2.7.13。

3个回答

8
不要调用字典中的函数;应该调用字典查找的结果。
dictionary = { 1: test1, 2: test2, 3: test3 }
dictionary[2]()

3

在创建字典时省略函数调用,直接调用dictionary[2]返回的值:

def main():
  dictionary = { 1: test1, 2: test2, 3: test3 }
  dictionary[2]()

3

下面的代码行实际上调用每个函数并将结果存储在字典中:

dictionary = { 1: test1(), 2: test2(), 3: test3() }

这就是为什么您看到了三行输出。每个函数都被调用。由于这些函数没有返回值,因此字典中存储了值 None 。打印它 (print(dictionary)):

{1: None, 2: None, 3: None}

相反,将函数本身存储在字典中:

dictionary = { 1: test1, 2: test2, 3: test3 }

print(dictionary)的结果如下:

{1: <function test1 at 0x000000000634D488>, 2: <function test2 at 0x000000000634D510>, 3: <function test3 at 0x000000000634D598>}

然后使用字典查找获取函数,然后调用它:

dictionary[2]()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接