擅长:python、mysql、java
<p>在对象创建之前,无法引用它。但是,可以在创建对象后修改<code>exits</code>字典,以便在文件室之间创建链接。一个很好的方法是让您创建的第二个房间通过一个附加参数自动创建一些回自身的链接:</p>
<pre><code>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
</code></pre>
<p>然后你会把一个额外的字典传递给后面房间的构造器,让它把链接从前面房间设置回自己:</p>
<pre><code>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
</code></pre>