.get不能在Python中工作

时间:2015-09-08 08:08:51

标签: python dictionary

import os


name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "@" + server


def error(choice):
        print(choice + ": command not found")
        commands()


def clear():
        os.system("cls")
        commands()


def commands():
        while 1 > 0:
                choice = input(prompt)
                {'clear': clear}.get(choice, error(choice))()

commands()

运行此代码时,无论我输入字典.get函数总是返回错误。当我进入'清除'该脚本应该转到该函数。有谁知道为什么这不能正常工作?感谢。

2 个答案:

答案 0 :(得分:3)

您将始终看到错误,因为必须在调用函数之前评估函数的所有参数。因此,error(choice)将被调用以在将结果作为默认值传递给get()之前获取其结果。

相反,请忽略默认值,并明确检查:

result = {'clear': clear}.get(choice)
if result:
    result()
else:
    error(choice)

答案 1 :(得分:1)

您不想实际拨打error(choice)

您可以partially apply parameters to a function但稍后再调用它:

>>> def error(choice):
...     print(choice + ': command not found')

>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found

所以你想要:

{'clear': clear}.get(choice, partial(error, choice))()