Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3中其他函数中未调用的函数_Python_Python 3.x - Fatal编程技术网

Python3中其他函数中未调用的函数

Python3中其他函数中未调用的函数,python,python-3.x,Python,Python 3.x,我的任务是模仿流程图创建一个“冒险”游戏 这是基于打开两个俄罗斯玩偶,一个绿色的,有一个打开蓝色玩偶的钥匙。第一个功能选择玩偶1或玩偶2之间的用户输入,并将用户转发到第二个功能或重新启动第一个方法中显示的选项 我的问题是,当我在调用这些函数(choice()或choice2())时,它们会显示错误 class main: global key key = False def choice2(): if (key == True): print("Co

我的任务是模仿流程图创建一个“冒险”游戏

这是基于打开两个俄罗斯玩偶,一个绿色的,有一个打开蓝色玩偶的钥匙。第一个功能选择玩偶1或玩偶2之间的用户输入,并将用户转发到第二个功能或重新启动第一个方法中显示的选项

我的问题是,当我在调用这些函数(choice()或choice2())时,它们会显示错误

class main:

  global key
  key = False

  def choice2():
    if (key == True):
      print("Congratulations, you have found the golden token.")
    else:
      print("Find the key first")
      choice()

  def choice():
    c1 = input("1. Blue Doll or 2. Green Doll?")

    if (c1 == 2):
      print("The doll contains a small key. You take the key")
      key = True
      choice()

    elif (c1 == 2):
      choice2()

  print("There is a green Russian doll and a blue Russian doll on the table.")
  choice()
当运行时,它显示初始问题(有一个蓝色/绿色的玩偶,你想打开哪个玩偶),当我键入1时,代码中断并停止,而不是转到下一部分。当我输入2时,这是我得到的错误(在repl.it上编码)

回溯(最近一次呼叫最后一次):
文件“main.py”,第1行,在
russianDoll类:
文件“main.py”,第25行,俄语
选择()
文件“main.py”,第22行,在选项中
选择2()
NameError:未定义全局名称“choice2”

您似乎已将所有函数放在一个类中,但仍试图将它们作为独立函数使用。也许您应该丢失这个类,因为它没有任何明确的用途。这不是Java。你不需要把所有的东西都塞进一个类中。
choice2
不是一个全局变量;这是一个类属性。只能通过
main
main
@chepner:的实例访问它,因为它们在定义类时正在运行方法,
main
实际上还不存在;他们根本不能调用
choice2
,除非是在顶级调用,就像他们调用
choice
一样。作为一名前Java程序员,这一问题一直困扰着我。两者都需要标记为@staticmethod,并且都需要被调用为main.choice()、main.choice2(),即使使用main。
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    class russianDoll:
  File "main.py", line 25, in russianDoll
    choice()
  File "main.py", line 22, in choice
    choice2()
NameError: global name 'choice2' is not defined