如何让 2 class 个实例相互引用?

How can I make 2 class instances refer to each other?

所以我在制作基于文本的游戏时遇到了一些问题。游戏通过引用一个函数的命令来运行,然后该函数会寻找玩家正在寻找的任何东西。例如 "examine item1" 将让它从位置的字典中打印 item1 的描述。

我遇到的问题是我无法使用当前布局设置播放器的位置。我想要发生的是玩家从洞穴开始,进入 go to forest 并且角色的位置设置为 forest。然而,它并没有达到这一点,因为无论我以哪种方式声明这两个,我都会遇到 NameError。我希望能够在两者之间移动。

cave = location(
    name = "CAVE NAME",
    desc = "It's a cave, there's a forest.",
    objects = {'item1' : item1, 'item2' : item2, 'item3' : item3},
    adjacentLocs = {'forest' : forest}
)
forest = location(
    name = "The Central Forest",
    desc = "It's very woody here. There's a cave.",
    objects = {},
    adjacentLocs = {'cave' : cave}
)

这是我的 goTo() 函数:

def goTo():
    target = None
    #Check inventory
    for key in pChar.inventory:
        if key.name.lower() in pChar.lastInput:
            print("\nThat's an object in your inventory. You won't fit in your backpack.")
            target = key
            break

    #Check scene objects
    if target == None:
        for key, loc in pChar.charLocation.objects.items():
            if key in pChar.lastInput:
                print("\nThat's a nearby object. You have essentially already gone to it.")
                target = key
                break

    #Check location list
    if target == None:
        for key, loc in pChar.charLocation.adjacentLocs.items():
            if key in pChar.lastInput:
                pChar.charLocation = loc
                print("\nYou amble on over to the {}.".format(pChar.charLocation.name))
                target = key
                break

    if target == None:
        print("That place doesn't exist.")

我如何最好地相互引用两个 类?

您不能引用一个对象,除非它已经存在。您可以分两次创建您的位置:首先,在没有任何相邻位置的情况下初始化它们。然后,定义相邻位置。类似于:

cave = location(
    name = "CAVE NAME",
    desc = "It's a cave, there's a forest.",
    objects = {'item1' : item1, 'item2' : item2, 'item3' : item3},
    adjacentLocs = {}
)
forest = location(
    name = "The Central Forest",
    desc = "It's very woody here. There's a cave.",
    objects = {},
    adjacentLocs = {}
)

cave.adjacentLocs["forest"] = forest
forest.adjacentLocs["cave"] = cave

(这是假设位置实例将它们的相邻位置分配给名为 adjacentLocs 的属性。您没有分享您的 class 实现,所以我不能确定这个细节。替换为任何合适的名称。)