__new__ 的单例模式在 python 中不起作用 2

singleton pattern with __new__ doesn't work in python 2

我尝试在 python 2 中实现单例模式,但它不起作用,但在 python 3 中有效,谁能帮我解释一下为什么?

class Singleton:

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()

print(obj1)
print(obj2)

输出:

<__main__.Singleton instance at 0x7fab8b625e60>
<__main__.Singleton instance at 0x7fab8b5e4710>

首先,在 python2 中,您必须从 object 继承才能使 __new__ 神奇。 因为 old-style class 根本没有 __new__ 方法。

因此,添加打印后您将得到:

>>> class Singleton:
...     _instance = None
...     def __new__(cls):
...         print('__new__')
...         if cls._instance is None:
...             print('create')
...             cls._instance = super().__new__(cls)
...         return cls._instance
... 
>>> obj1 = Singleton()
>>> obj2 = Singleton()
>>> 
>>> print(obj1)
<__main__.Singleton instance at 0x7f47dcccecb0>
>>> print(obj2)
<__main__.Singleton instance at 0x7f47dcccef80>

如您所见,python2 根本没有调用 __new__。它只是在您的情况下调用空 __init__ 并创建两个不同的对象。

其次,在 python2 中,您需要重写 super() 调用,因为它在 python3 中已更改。 所以更正后的代码将是:

>>> class Singleton(object):
...     _instance = None
...     def __new__(cls):
...         print('__new__')
...         if cls._instance is None:
...             print('create')
...             cls._instance = super(Singleton, cls).__new__(cls)
...         return cls._instance
... 
>>> obj1 = Singleton()
__new__
create
>>> obj2 = Singleton()
__new__
>>> 
>>> print(obj1)
<__main__.Singleton object at 0x7f47dccd9590>
>>> print(obj2)
<__main__.Singleton object at 0x7f47dccd9590>

有关单例的更多信息,请参阅此处:Creating a singleton in Python