两个课程有什么区别?他们的工作方式不同吗

hal*_*hal 1 python inheritance singleton class python-3.x

Singleton的这两个实现有什么区别.在父类中创建变量_instance是否使其与第二个类的工作方式不同?

class SingletonA(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


class SingletonB(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


# sample usage
class A(SingletonA):
    pass


print(A() == A()) #True
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

对于发布的代码,没有区别.

如果您的子类实现__bool__或者__len__,第一个示例将失败,即使已经设置了实例也not self._instance可能返回True.你真的想用if self._instance is None::

>>> class AlwaysFalse(object):
...     def __bool__(self): return False
...
>>> if not AlwaysFalse():
...     print("It doesn't exist? Should we create a new one?")
...
It doesn't exist? Should we create a new one?
>>> AlwaysFalse() is None
False
Run Code Online (Sandbox Code Playgroud)

除此之外,差异是美化.

您还希望使用身份测试来检查单例实现是否正常工作; 子类可以实现该__eq__方法并返回True即使两个对象是不同的(所以不是单例):

>>> class EqualNotSingleton(object):
...     def __eq__(self, other): return True
...
>>> EqualNotSingleton() == EqualNotSingleton()
True
>>> EqualNotSingleton() is EqualNotSingleton()
False
Run Code Online (Sandbox Code Playgroud)