【问题标题】:child class as singleton [closed]子类作为单身人士[关闭]
【发布时间】:2021-11-08 15:39:30
【问题描述】:

在python中,我想设计两个类:

  1. A 类将有一组方法。
  2. B 类将具有 A 的所有方法并且是单例。

我是这样写的:

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 A:
    def __init__(self, toto):
        self.toto = toto

    def another_method(self):
        ...


class B(A, metaclass=Singleton):
    pass

这是定义 A 和 B 的正确方法吗?

【问题讨论】:

    标签: python design-patterns singleton


    【解决方案1】:

    确实是一种可能的方式,不是唯一的。

    当元类可以在许多类中被重用时,使用元类是有意义的。在这里你也可以使用 A 中的__new__ 方法:

    class A:
        _instances = {}
        def __new__(cls, toto):
            if cls is A:
                obj = object.__new__(cls)
                obj._do_init(toto)
            elif cls not in A._instances:
                A._instances[cls] = object.__new__(cls)
                A._instances[cls]._do_init(toto)
            return A._instances[cls]
    
        # initialization is moved from the special __init__ method to
        # a private one to prevent subsequent "creations" to change the
        # initial value of the singleton
        def _do_init(self, toto):
            self.toto = toto
    
    class B(A):
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多