This question is not for the discussion of whether or not the singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. 这个问题不是为了讨论是否须要单例设计模式 ,是不是反模式,仍是针对任何宗教战争,而是要讨论如何以最pythonic的方式在Python中最好地实现此模式。 In this instance I define 'most pythonic' to mean that it follows the 'principle of least astonishment' . 在这种状况下,我定义“最pythonic”来表示它遵循“最少惊讶的原理” 。 python
I have multiple classes which would become singletons (my use-case is for a logger, but this is not important). 我有多个将成为单例的类(个人用例用于记录器,但这并不重要)。 I do not wish to clutter several classes with added gumph when I can simply inherit or decorate. 当我能够简单地继承或修饰时,我不但愿增长gumph来使几个类杂乱无章。 设计模式
Best methods: 最佳方法: 函数
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
Pros 优势 ui
Cons 缺点 this
m = MyClass(); n = MyClass(); o = type(n)();
一样对于m = MyClass(); n = MyClass(); o = type(n)();
m = MyClass(); n = MyClass(); o = type(n)();
then m == n && m != o && n != o
而后m == n && m != o && n != o
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass
Pros 优势 spa
Cons 缺点 .net
__new__
could be overwritten during inheritance from a second base class? __new__
是否能够在从第二个基类继承时被覆盖? One has to think more than is necessary. 人们必须思考的超出了必要。 class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] #Python2 class MyClass(BaseClass): __metaclass__ = Singleton #Python3 class MyClass(BaseClass, metaclass=Singleton): pass
Pros 优势 设计
__metaclass__
for its proper purpose (and made me aware of it) 将__metaclass__
用于其适当的目的(并使我意识到这一点) Cons 缺点 code
def singleton(class_): class class_w(class_): _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w @singleton class MyClass(BaseClass): pass
Pros 优势 对象
Cons 缺点
_sealed
attribute _sealed
属性的意义是什么 super()
because they will recurse. 没法使用super()
在基类上调用相同名称的方法,由于它们会递归。 This means you can't customize __new__
and can't subclass a class that needs you to call up to __init__
. 这意味着您不能自定义__new__
,也不能将须要调用__init__
类做为子类。 a module file singleton.py
一个模块文件singleton.py
Pros 优势
Cons 缺点