Skip to main content
 首页 » 编程设计

python之两个呈现的类之间有什么区别他们的工作方式不同吗

2025年05月04日11lexus

单例的这两种实现有什么区别。在父类中创建变量 _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__ method并返回 True,即使这两个对象是不同的(所以不是单例):

>>> class EqualNotSingleton(object): 
...     def __eq__(self, other): return True 
... 
>>> EqualNotSingleton() == EqualNotSingleton() 
True 
>>> EqualNotSingleton() is EqualNotSingleton() 
False