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
对于发布的代码,没有区别。
但是,如果您的子类实现__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
除此之外,差异是装饰性的。
您还想使用身份测试来检查单例实现是否正常工作;即使两个对象不同(因此不是单例),子类也可以实现该__eq__
方法并返回True
:
>>> class EqualNotSingleton(object):
... def __eq__(self, other): return True
...
>>> EqualNotSingleton() == EqualNotSingleton()
True
>>> EqualNotSingleton() is EqualNotSingleton()
False
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句