我试着用Python制作一个简单的文本游戏。我有一个班级:

class Room():
    def __init__(self, monster, exits, loot):
        self.room_guard = monster
        self.exits = exits
        self.guard_is_alive = True
        self.loot = loot

当我创建文件室时,我会收到一个错误,因为在创建之前我会这样调用它们:
room_2 = Room(spider, {"West": room_3, "East": room_4, "South": room_1}, 2)
room_1 = Room(trogdor, {"North": room_2}, 2)

房间2不能有Room,因为它没有被实例化。有办法解决这个问题吗?

最佳答案

两个选项:间接,创建后分配。
与其直接引用房间,不如使用将房间名称映射到房间的dict

rooms = {}
rooms['room_2'] = Room(spider, {"West": 'room_3', "East": 'room_4', "South": 'room_1'}, 2)
rooms['room_1'] = Room(trogdor, {"North": 'room_2'}, 2)

或在创建房间对象之后分配出口:
room_2 = Room(spider, {}, 2)
room_1 = Room(trogdor, {}, 2)

room_2.exits = {"West": room_3, "East": room_4, "South": room_1}
room_1.exits = {"North": room_2}

关于python - 在实例化类之前,有没有办法引用类对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29382373/

10-11 21:08