从其他对象实例访问对象实例的模式

Pattern to access to object instance from other object instances

提前致谢。鉴于 类...

的这些示例


    # registers all that happens during a combat
    class CombatLog:
        def __init__(self):
            self.actions = []

    # it handles a combat
    class Combat:
        def __init__(self):
            self.fighters = []   # list of fighter instances
            self.combat_log = CombatLog()
        def run_round(self):
            # do whatever
            self.combat_log.log(...)

    # are the fighters in a combat
    class Fighter:
        def __init__(self):
            self.property1 = 1
            self.property2 = 2
            self.attacks = []  # list of attack instances
        def attack(self):
            # do whatever
            self.combat_log.log(...)  # clean way to access the log?

    class Attack:
        def __init__(self):
            self.damage = 10
        def cast(self):
            # do whatever
            self.combat_log.log(...)  # clean way to access the log?


    # from somewhere else in the code
    combat1 = Combat()
    combat2 = Combat()

我想知道处理下一个要求的最佳模式是什么:

我正在考虑的方法,但我不是 proud/sure 中的方法:

也许我需要另一种方法,但我想不出...代码在Python.

非常感谢您的宝贵时间。

还有另一种简单的方法,无论如何我认为最好的选择是在引用对象 Combat 的其他对象中有一个指针,但这似乎不可能:
Pointers in Python?
您可以维护一个 Combats 字典并将它们的密钥传递给它们自己和其他对象:

combats = {uuid0: Combat(), uuid1: Combat()}

并像

一样访问它们
class Attack:
    def __init__(self, combatUUID = None):
        self.damage = 10
        if combatUUID: self.combatUUID = combatUUID 
    def cast(self):
        # do whatever
        if self.combatUUID in combats: combats[self.combatUUID].log(...)

如果一个战士只存在于一场战斗中,让它知道它在哪场战斗中:

class Fighter:
    def __init__(self, combat, name):
        self.name = name
        self.combat = combat
    def attack(self):
        self.combat.log.append('{name} attacking'.format(name=self.name))

如果一个战士可以切换战斗,添加一个战斗setter:

class Figthter:
    # init(self, name) ...

    def set_combat(combat):
        self.combat = combat