【问题标题】:Why the function calling does not work in python in a dictionary为什么函数调用在字典中的python中不起作用
【发布时间】:2020-03-12 01:04:55
【问题描述】:

我正在调用字典中的函数。在下面的代码中,select.get 没有按预期工作。如果inum = 2,它仍然会执行login()

感谢任何帮助找出问题所在!

def menu():
    print("Choose\n1.Log in\n2.Exit")
    inum = input()
    select = {
        1: login(),
        2: exit(),
    }
    select.get(inum, menu())


def login():
    guess = ""
    acct = "12345"
    oog = 3
    out = 0
    while guess != acct:
        if oog == out:
            print("no trys left")
            input()
            exit()

        print((str(oog)) + "trys left " + "\nEnter Password here: ")
        guess = input()
        oog = oog - 1

menu()

【问题讨论】:

  • 当您分配给select 时,您正在调用login()exit()

标签: python function dictionary select


【解决方案1】:

您没有调用用户选择的函数。您将立即调用这两个函数,并将它们的返回值放入字典中。

当您调用select.get() 时,您正在递归调用menu(),没有任何终止条件。

您需要将函数放入字典中,而不是它们的返回值。然后调用select.get() 返回的内容。

而且由于input()返回的是字符串,所以需要使用字符串作为字典中的键。

def menu():
    print("Choose\n1.Log in\n2.Exit")
    inum = input()
    select = {
        '1': login,
        '2': exit,
    }
    select.get(inum, menu)()

【讨论】:

  • 如果第一个函数(登录)需要传入参数而第二个(退出)没有参数怎么办?
  • 你可以使用 lambdas。
【解决方案2】:

如果你想做这样的事情,你需要传递对函数的引用,而不是调用函数的结果。然后您可以在进行选择时使用这些功能。例如:

def menu():
    inum = input("Choose\n1.Log in\n2.Exit\n")
    select = {
        '1': login,
        '2': exit,
    }

    # decide which function and call it with ()
    select.get(inum, menu)() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2021-09-03
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多