在 python 中,如何在不同对象之间共享(引用)一个变量作为属性?

In python, how to share (the reference of) a variable as attributes across different objects?

所以我有一个主要的class和几个辅助的class。在主 class 的方法中,我需要一些辅助对象,我想用它们 "share" 主实例的 shared_data 属性,这样每当我更改 shared_data 主对象的属性,辅助对象的相应属性也会相应更新。 (具体来说,您可以将 shared_data 视为 "time",我希望 "time" 属性在各种对象之间保持同步。

然而,看起来像下面这样天真的方式这样做是行不通的,因为那实际上不会 "share" 跨对象的数据,而只是将当前值分配给这些对象,所以这些对象属性不会保持同步。实现此 "syncing" 或 "sharing" 功能的正确方法应该是什么?

class Main:

    def __init__(self, shared_data):
        self.shared_data = shared_data
        pass

    def do_stuff(self):
        # initialise auxiliary objects (only for once).
        # hopefully when self.x1 is changed, the data in
        # the objects aux1, aux2 will also reflect this change
        aux1, aux2 = Aux1(self.shared_data), Aux2(self.shared_data)

        # however, in general, changing self.shared_data would not
        # change the data in aux1 or aux2
        another_value = ...
        self.shared_data = another_value    # doesn't work

        pass


class Aux1:

    def __init__(self, x1):
        self.x1 = x1
        ...
        pass


class Aux2:

    def __init__(self, x2):
        self.x2 = x2
        ...
        pass

除此部分外一切正常:

self.shared_data = another_value    # doesn't work

该行不修改 shared_value。它只是将一个不同的对象分配给之前持有共享数据对象的变量。

您需要做的是修改 shared_value,例如这样:

self.shared_value.data = another_data

这是一个完整的例子:

class SharedData:
    def __init__(self):
        self.time = 0
        self.colour = "red"


class ObjectWithSharedData:
    def __init__(self, shared_data):
        self._shared_data = shared_data

    def do_stuff(self):
        self._shared_data.time = 7

    def get_time(self):
        return self._shared_data.time


shared_data = SharedData()
a = ObjectWithSharedData(shared_data)
b = ObjectWithSharedData(shared_data)
c = ObjectWithSharedData(shared_data)

a.do_stuff()

print(a.get_time())  # prints 7
print(b.get_time())  # prints 7
print(c.get_time())  # prints 7