我不明白为什么我会收到 AttributeError

I cannot figure out why I am getting AttributeError

亲爱的 Whosebug 天使,

我真的被这个问题困住了。我正在编写游戏代码并收到此错误消息:

File "VillageGame.py", line 120, in <module>
launch.play()
File "VillageGame.py", line 84, in play
returned_scene = future_scene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'

错误消息引用的代码如下:

class Room(object):

    def __init__(self):
        pass

    def enter(self):
        pass  

class Road(Room): 

    def __init__(self):
        pass

    def enter(self):
        pass  

    def walk(self): 
        print "It is afternoon and you stand by the road of Red Village. It is a small, run-down place"
        print "with a few shops and houses. A few residents walk about. It is a quiet place. You need"
        print "to steal gold to feed yourself and pay your rent. This evening you need to steal 800 gold"
        print "to pay your rent and bills. There are houses and businesses in the area. But plan carefully,"
        print "the police here are armed and the locals are suspicious of odd outsiders like yourself. But"
        print "you can fight, which should help. In front of you is a food shop, a weapons shop,"
        print "a medicine shop, a bank and an inn. Where would you like to go first?" 
        return 'road' 

    def run(self): 
        pass        



class Engine(object):

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

    def play(self):

        future_scene = self.game_map.launch_scene()
        last_scene = self.game_map.next_scene('finished') 

        while future_scene != last_scene:
            returned_scene = future_scene.enter() 
            future_scene = self.game_map.next_scene(returned_scene)

        # make sure you run the last scene
        future_scene.enter()



class Map(object):

    rooms = {
        'road' : Road(),
        'food_shop' : FoodShop(),
        'weapons_shop' : WeaponsShop(),
        'medicine_shop' : MedicineShop(),
        'bank' : Bank(),
        'inn' : Inn(),  
        'death' : Death(),
        'finished' : Finished() 
        }        


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

    def next_scene(self, returned_scene):
        val = Map.rooms.get(returned_scene)
        return val

    def launch_scene(self):
        return self.next_scene(self.start_scene) 



firstscene = Map('road') 
launch = Engine(firstscene) 
launch.play() 

抱歉,如果这看起来像是代码转储,但我不知道哪些部分与错误消息相关,哪些部分与其无关 - 因为我对此很陌生,你看。

如果有人知道我可以从这条消息中删除哪些代码,我也将不胜感激。这将帮助我缩短以后的问题。

问题是Map('road')returnsNone。我想你想做的是这个。

map = Map('road') 
firstscene = map.launch_scene()
launch = Engine(firstscene) 
launch.play()

但即使这样也不完全正确。下面的行没有实例化地图。

val = Map.rooms.get(returned_scene)

如果要从 class 中调用 Map class 的函数,请使用 self 关键字,例如 self.rooms.get(returned_scene)

这一行 returned_scene = future_scene.enter() 需要一个 return 值,但你还没有在方法中实现任何东西def enter(self)(你只是 pass-ing 它,并且所以它 return 是一个 None 对象。