使用从其他模块导入的元类时的析构函数顺序

时间:2020-04-22 10:56:10

标签: python python-3.x destructor

我想在python中使用单例模式。这是它的代码:

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

我想使用它作为元类,例如:

class Foo(metaclass=Singleton):
  def __init__(self):
      self._test_list = {}

  def __del__(self):
      self._test_list = {}

def main():
   test = Foo()

我对析构函数的归纳顺序有疑问。我将打印品添加到Foo类的 del 和Singleton中。当我在同一.py脚本中具有Singleton元类和Foo类时,打印顺序为:

del singleton
del Foo

但是当我从其他模块中以简单的行from module_path import Singleton导入Singleton时,顺序更改为:

del Foo
del singleton

在我的代码中,这是关键的区别,因为对于第二个选项,代码不起作用(特定于外部库),但是文件组织不直观。

  1. 为什么会这样?
  2. 如何确保一个正确的析构函数顺序?

整个代码:

#I use these line with exactly the same Singleton metaclass implementation in module_path
from module_path import Singleton
#Or this Singleton implementation inside the same file as Foo class
class Singleton(type):
   _instances = {}

   def __call__(cls, *args, **kwargs):
      if cls not in cls._instances:
          cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
      return cls._instances[cls]

  def __del__(cls):
      print('del singleton')

class Foo(metaclass=Singleton):
    def __init__(self):
        self._test_list = {}

    def __del__(self):
        print('del Foo')
        self._test_list = {}


def main():
    test = Foo()

0 个答案:

没有答案