在实例化类对象之前,有没有一种方法可以引用它?

2024-04-16 23:42:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python做一个简单的文本游戏。我有一个Room类:

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不能有"South": room_1,因为它还没有被实例化。有办法吗?你知道吗


Tags: 文本self游戏initisdefclassroom
3条回答

两个选项:间接、创建后赋值。你知道吗

不要直接引用文件室,而是使用将文件室名称映射到文件室的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}

在对象创建之前,无法引用它。但是,可以在创建对象后修改exits字典,以便在文件室之间创建链接。一个很好的方法是让您创建的第二个房间通过一个附加参数自动创建一些回自身的链接:

class Room():
    def __init__(self, monster, exits, loot, exits_back={}):
        self.room_guard = monster
        self.exits = exits
        self.guard_is_alive = True
        self.loot = loot
        for direction, room in exits_back.items():
            room.exits[direction] = self

然后你会把一个额外的字典传递给后面房间的构造器,让它把链接从前面房间设置回自己:

room_2 = Room(spider, {"West": room_3, "East": room_4}, 2)        # no room_1 ref here
room_1 = Room(trogdor, {"North": room_2}, 2, {"South": room_2})   # extra dict passed

我能想象的最好的方法是创建对象,然后分两个不同的步骤创建链接。你知道吗

class Room(object):
    def __init__(self, monster, loot):
        self.exits = {direction:None for direction in
                      ["North", "South", "East", "West"]}
        # rooms have no exits until you add links to them manually
        self.room_guard = monster
        self.guard_is_alive = True
        self.loot = loot
    def add_link(self, other, ordinal):
        """Creates a link between this room and another in the specified direction

        room_A.add_link(room_B, 'East')
        sets room_A.exits['East'] = room_B and room_B.exits['West'] = room_A"""

        if not hasattr(other, 'exits')
            raise ValueError("Can only link with other objects with exits")
        ordinal_map = {"North":"South", "South":"North",
                       "East":"West", "West":"East"}
        try:
            other_ordinal = ordinal_map[ordinal]
        except KeyError:
            raise ValueError("ordinal must be one of {}".format(
                    ', '.join(ordinal_map.keys())))

        self.exits[ordinal] = other
        other.exits[other_ordinal] = self

先整理房间

map = """  A - B   C
           |       |
           D - E - F """
# bonus points if you can build a function that takes this as input and
# outputs the correct structure of rooms!!!

rooms = {key:Room(*args) for key,args in zip("ABCDEF",monster_loot_tuples)}
# monster_loot_tuples would be a list like [("Gargoyle","+1 Sword of Smiting"), ...]

然后添加链接

rooms['A'].add_link(rooms['B'], 'East')
rooms['A'].add_link(rooms['D'], 'South')
rooms['D'].add_link(rooms['E'], 'East')
rooms['E'].add_link(rooms['F'], 'East')
rooms['F'].add_link(rooms['C'], 'North')

相关问题 更多 >