单例类具有不同的分配地址

1 投票
1 回答
48 浏览
提问于 2025-04-14 15:32

在 a.py 这个文件里,它正在获取一些指标的值,并把这些值放到一个叫做字典的东西里。我想把这些值保存到 container.py 里的一个全局字典变量中,然后在 b.py 里使用它。

为此,我在 container.py 里声明了一个叫做 GlobalContainer 的单例,并在里面创建了一个字典。接着,在 a.py 中,我把获取到的值添加到了这个字典里。但是,当我在 b.py 中尝试访问这个单例里的字典时,发现里面没有值。经过检查,我发现 container.py 中的 GlobalContainer 的内存地址是不同的。

我需要一个可以从 a.py、b.py、c.py 等文件中都能访问的数据存储。我不明白为什么单例的地址会不同。

container.py

class Singleton:
  def __init__(self, decorated):
    self._decorated = decorated
    self._initialized = False  # Flag for first instance creation

  def instance(self):
    if not self._initialized:
      self._instance = self._decorated()
      self._initialized = True
    return self._instance

  def __call__(self):
    raise TypeError('Singletons must be accessed through `instance()`.')

  def __instancecheck__(self, inst):
    return isinstance(inst, self._decorated)

  def __wrap__(self, instance, objtype, wrapper):
    # Allow access to class methods using the actual class object (cls)
    instance.__getattribute__ = lambda self, name: getattr(objtype, name, self.__dict__[name])
    return wrapper(instance)

@Singleton
class GlobalContainer:
    containers = {}

    def __init__(self):
    # No initialization check needed here
        print("### GlobalContainer created")  # This will print only once

    @classmethod
    def set_indicators(cls, symbol, indicators):
        if symbol not in cls.containers:
            cls.containers[symbol] = {'indicators': indicators}
        else:
            cls.containers[symbol]['indicators'] = indicators

    @classmethod
    def get_indicators(cls, symbol):
        container = cls.containers.get(symbol, {})
        return container.get('indicators', None)

在 a.py 中

GlobalContainer.instance().set_indicators(self.symbol, self.indicators)

在 b.py 中

GlobalContainer.instance().get_indicators(symbol)

单例的初始化部分里有一句 print('### GlobalContainer created') 被执行了两次。我只想创建一个实例,并把它作为 GlobalContainer 的全局变量来使用。

1 个回答

0

“单例”有两个不同的地址,是因为你在运行两个不同的脚本,每个脚本在启动时都定义了一个新的 GlobalContainers 类。这个类在两个不同的进程之间是 共享的。

撰写回答