What are the differences between the following two implementations of singleton design pattern in Python?
What are the differences between their intended usages?
From Python in a Nutshell
class Singleton(object):
_singletons = {}
def __new__(cls, *args, **kwds):
if cls not in cls._singletons:
cls._singletons[cls] = super(Singleton, cls).__new__(cls)
return cls._singletons[cls]
any subclass of Singleton
(that does not further override __new__
) has exactly one instance.
From Usage of super in singleton
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
Aucun commentaire:
Enregistrer un commentaire