繁体   English   中英

声明变量运行而不运行

[英]Declare variable to function without running it

def user(choose):
    if (choose == "1"):
        play = game()
    elif (choose == "2"):
        return stats(play)
    else:
        return quit()

我想从game()函数中获取值并在stats()中使用它,但是我收到一条错误消息,说未定义游戏。 如何声明game()并在另一个函数中使用它?

您可以“推迟”执行func1

def func1():
    return 'abc'

def something_else(callable):
    callable()

def main():
    hello = None

    def f():
        """set result of func1 to variable hello"""
        nonlocal hello
        hello = func1()

    # over here func1 is not executed yet, hello have not got its value
    # you could pass function f to some other code and when it is executed, 
    # it would set result for hello 
    print(str(hello))  # would print "None"
    call_something_else(f)
    print(str(hello))  # would print "abc"

main()

问题改变之后...

现在,您的本地变量play超出了统计范围。 此外,看起来您希望该函数将被调用两次。 您需要将play内容保存在全局内容中

play = None  # let's set it to some default value
def user(choose):
    global play  # let python know, that it is not local variable

    if choose == "1":  # no need for extra brackets
        play = game()

    if choose == "2" and play:  # double check that play is set
        return stats(play)

    return quit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM