[英]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.