gpt4 book ai didi

python - 名称错误 : name 'MainCorridor' is not defined

转载 作者:行者123 更新时间:2023-12-01 04:42:17 25 4
gpt4 key购买 nike

我正在学习 LPTHW,并致力于制作自己的游戏。

class Engine(object):

location_dict = {
'main_corridor': MainCorridor(),
}

def goto(self, location):
return Engine.location_dict.get(location).start()

def test(self):
print "Calling Engine() from MainCorridor()"


class MainCorridor(object):

def __init__(self):
self.engine = Engine()

def start(self):
self.engine.test()



game = Engine()
game.goto('main_corridor')

有人可以建议我如何解决这个问题吗?非常感谢,谢谢

这是错误消息:

Traceback (most recent call last):
File "ex45_game.py", line 1, in <module>
class Engine(object):
File "ex45_game.py", line 4, in Engine
'main_corridor': MainCorridor()
NameError: name 'MainCorridor' is not defined

最佳答案

我最近做了 lpthw 教程。 Zed 所做的是创建第三个类来映射游戏中的级别,这样可以在定义其余类后实例化它们。这应该可以修复“未定义”错误。

但另一个问题是您最后要创建一个引擎对象:

game = Engine()

然后,当您初始化 MainCorridor 类时,您将创建一个单独的引擎对象:

class MainCorridor(object):

def __init__(self):
self.engine = Engine()

解决方案是仅在 MainCorridor 类中创建引擎类:

class Engine(object):

def test(self):
print "Calling Engine() from MainCorridor()"


class MainCorridor(object):

def __init__(self):
self.engine = Engine()

def start(self):
self.engine.test()


class Map(object):

location_dict = {
'main_corridor': MainCorridor(),
}

def goto(self, location):
map = self.get_location(location)
return map.start()

def get_location(self, location):
return self.location_dict[location]


game = Map()
game.goto('main_corridor')

但是这样,您放入 location_dict 中的每个位置实例都将拥有自己唯一的 Engine 对象。

要为每个位置提供单个引擎对象,您可以将“self”从引擎传递到 map 类,并让 map 类通过将相同的引擎对象传递到列表中的每个位置来实例化 location_dict:

class Engine(object):

def __init__(self):
self.map = Map(self)

def test(self):
print "Calling Engine() from MainCorridor()"


class MainCorridor(object):

def __init__(self, engine):
self.engine = engine

def start(self):
self.engine.test()


class Map(object):

def __init__(self, engine):
self.location_dict = {
'main_corridor': MainCorridor(engine),
}

def goto(self, location):
map = self.get_location(location)
return map.start()

def get_location(self, location):
return self.location_dict[location]


game = Engine()
game.map.goto('main_corridor')

关于python - 名称错误 : name 'MainCorridor' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30325038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com