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

问题描述 投票:0回答:1

所以我在使用基于文本的游戏时遇到了一些问题。游戏通过接受引用函数的命令来操作,然后该函数查找玩家正在寻找的任何内容。例如,“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.")

我怎样才能最好地引用彼此之间的两个类?

python class reference variable-declaration
1个回答
1
投票

除非已存在,否则无法引用该对象。您可以通过两次传递创建您的位置:首先,在没有任何相邻位置的情况下初始化它们。然后,定义相邻的位置。就像是:

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的属性。您没有共享您的类实现,因此我无法确定这个细节。以任何名称替换都是合适的。)

© www.soinside.com 2019 - 2024. All rights reserved.