Python:无法从另一个对象内部实例化我的对象:'global name not defined'

Python: can't instantiate my object from inside another object: 'global name not defined'

大家好,在此先感谢您的帮助。

我正在学习 Python 并正在制作 Zork 风格的冒险游戏进行练习。

一旦我定义了 类 我的第一个实际指令是

ourGame = Game('githyargi.txt')

其中 githyargi.txt 是一个包含所有游戏字符串的文件。方法 Game.parseText() 按照记录工作。

回溯显示问题:

Traceback (most recent call last):
  File "githyargi.py", line 237, in <module>
    ourGame = Game('githyargi.txt')
  File "githyargi.py", line 12, in __init__
    self.scenes[0] = Start()
  File "githyargi.py", line 166, in __init__
    for string in ourGame.strings['FIRST']:
NameError: global name 'ourGame' is not defined

如果我从执行块中执行 ourGame.scenes[0] = Start() 它会很好用 - 没有名称错误,并且 self.scenes[0].flavStr 会填充适当的风格文本。但是我想创建一个方法 Game.makeScenes() 来创建游戏中的所有场景并将它们存储在列表 ourGame.scenes 中。为什么 Start() 的 init 从 Game() 的 init 实例化时看不到 ourGame.strings,当它可以看到从执行块实例化时是同一个字典吗?

class Game(object):

    def __init__(self, filename):
        '''creates a new map, calls parseText, initialises the game status dict.'''
        self.strings = self.parseText(filename)
        self.sceneIndex = 0
        self.scenes = []
        self.scenes[0] = Start()
        self.status = {
            "Health": 100,
            "Power": 10,
            "Weapon": "Unarmed",
            "Gizmo": "None",
            "Turn": 0,
            "Alert": 0,
            "Destruct": -1
            }

    def parseText(self, filename):
        '''Parses the text file and extracts strings into a dict of
        category:[list of strings.]'''
        textFile = open(filename)
        #turn the file into a flat list of strings and reverse it
        stringList = []; catList = [] ; textParsed = {}
        for string in textFile.readlines():
            stringList.append(string.strip())
        stringList.reverse()

        #make catList by popping strings off stringList until we hit '---'
        for i in range(0, len(stringList)):
            string = stringList.pop()

            if string == '---':
                break
            else:
                catList.append(string)

        #Fill categories
        for category in catList:
            newList = []
            for i in range(0, len(stringList)):
                string = stringList.pop()

                if string == '---':
                    break
                else:
                    newList.append(string)

            textParsed[category] = newList

        return textParsed

class Scene(object):

    def __init__(self):
        '''sets up variables with null values'''
        self.sceneType = 'NULL'
        self.flavStr = "null"
        self.optStr = "null"
        self.scenePaths = []

class Start(Scene):

    def __init__(self):
        self.flavStr = ""
        for string in ourGame.strings['FIRST']:
            self.flavStr += '\n'
            self.flavStr += string
        self.optStr = "\nBefore you lies a dimly lit corridor. (1) to boldly go."
        self.scenePaths = [1]

这是一个时间问题。当你这样做时

ourGame = Game('githyargi.txt')

然后首先创建Game实例,然后才分配给ourGame。

相反,将 Game 传递给 Scene 的构造函数,然后传递 self,这样它就变成了

self.scenes.append(Start(self))

请注意,您也不能执行 scenes = [] 然后在下一行设置 scenes[0] -- 空列表没有元素 0。