通过全局函数调用嵌套函数



我是Python的新手,正在尝试制作一个包含几个章节的简单游戏。我希望你能够根据章节做不同的事情,但总是能够检查你的库存。这就是我尝试使用嵌套函数的原因。

是否有可能创建一个全局函数,根据我所在的章节采取不同的行动,同时在所有章节中都有某些选项,或者我是否应该大幅重组我的代码?

我得到以下错误代码:

> Traceback (most recent call last):   File "test.py", line 21, in
> <module>
>     chapter1()   File "test.py", line 19, in chapter1
>     standstill()   File "test.py", line 4, in standstill
>     localoptions() NameError: name 'localoptions' is not defined

我知道全局函数不能识别嵌套函数。有没有办法将这个嵌套函数指定为全局函数?

def standstill():
print("What now?")
print("Press A to check inventory")
localoptions()
choice = input()
if choice == "A":
print("You have some stuff.")
else:
localanswers()
def chapter1():
def localoptions():
print("Press B to pick a flower.")
def localanswers():
if choice == "B":
print("What a nice flower!")
standstill()
chapter1()

我按照Mateen Ulhaq的建议使用了类并解决了它。谢谢!这是一个可扩展的游戏系统的例子。

(我是Python新手,这可能不是最好的方法,但我现在就是这样解决的。(

class chapter1:
option_b = "Pick a flower."
def standstill():
print("What do you do now?")
print("A: Check inventory.")
if chapter1active == True:
print("B: " + chapter1.option_b)
#Chapter 1
chapter1active = True
standstill()
chapter1active = False

最新更新