使用函数值访问python dict

use*_*494 3 python dictionary function

我试图在python中创建一个选项菜单,如果用户选择一个数字,则执行不同的函数:

def options(x):
    return {
        1: f1(),
        2: f2()
    }[x]

def f1():
    print "hi"

def f2():
    print "bye"
Run Code Online (Sandbox Code Playgroud)

但是,我打电话

options(1)
Run Code Online (Sandbox Code Playgroud)

我明白了:

hi
bye
Run Code Online (Sandbox Code Playgroud)

和我打电话时一样 options(2)

到底是怎么回事?

the*_*eye 7

您正在调用函数,而不是根据键分配它们

def f1():
  print "hi"

def f2():
  print "bye"

functions = {1: f1, 2: f2}  # dict of functions (Note: no parenthesis)

def options(x):
    return functions[x]()   # Get the function against the index and invoke it

options(1)
# hi

options(2)
# bye
Run Code Online (Sandbox Code Playgroud)