这是python中单例的一个例子。我不明白的一件事是,我认为类中的_instance总是设置为 None,因此"如果不是cls._instance"应该始终为真,因此,不需要 if 语句。
我知道我错了,请帮助我错过的地方。
class Singleton(object):
_instance = None # Keep instance reference
# why do this???? If do this, the "if not .." state follow is always true, right?
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__name__(cls, *args, **kwargs)
return cls._instance
更新
我的困惑是:为什么第二次调用 Singleton(( 时,没有触发 _instance = None?而它是触发的第一个呼叫?
__new__
也是一个取代__init__
方法的类方法(您可以控制在此级别创建的对象(
_instance
是类属性,而不是实例属性。因此,在创建实例之前,它在__new__
方法中可见/可用。
所以第一次,cls._instance
参数是None
,所以__new__
创建实例并将结果存储在cls
的_instance
类属性中(这是你的Singleton
类(
它不会第二次None
,因为实例的引用已经存储,所以它返回相同的self._instance
对象。在此过程中,object.__new__
在类的生存期内仅调用一次。
这遵循了单例的设计模式:创建一次,每次返回相同的对象。
请注意,这是不正确的:
cls._instance = object.__name__(cls, *args, **kwargs)
应该是
cls._instance = object.__new__(cls, *args, **kwargs)
调用object.__name__
没有意义,因为它是一个字符串。从代码派生的小型独立示例:
class Singleton(object):
_instance = None # Keep instance reference
# why do this???? If do this, the if state follow is always false, right?
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
print("creating")
return cls._instance
a = Singleton()
b = Singleton()
print(a is b)
此代码输出:
creating
True
如您所见,它第一次创建对象,然后在第二次创建对象时返回相同的对象。
如果cls._instance
是None
,那么not cls._instance
是True
,而不是False
。