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

时间:2019-07-11 08:16:49

标签: python python-2.7 singleton

我尝试在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>

1 个答案:

答案 0 :(得分:1)

首先,在python2中,必须从对象继承才能使__new__神奇。 因为老式类根本没有__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