在Python中似乎有很多方法来定义单例对象。对Stack Overflow是否有一致的意见?


当前回答

我真的不认为有这个需要,因为一个带有函数(而不是类)的模块可以很好地作为一个单例。它的所有变量都将绑定到模块,无论如何都不能重复实例化。

如果你确实希望使用一个类,在Python中没有办法创建私有类或私有构造函数,所以你不能防止多个实例化,只能通过使用API中的约定。我仍然会将方法放在模块中,并将模块视为单例模块。

其他回答

我对此非常不确定,但我的项目使用'惯例单例'(不是强制单例),也就是说,如果我有一个名为DataController的类,我在同一个模块中定义这个:

_data_controller = None
def GetDataController():
    global _data_controller
    if _data_controller is None:
        _data_controller = DataController()
    return _data_controller

它并不优雅,因为它足足有六行。但是我所有的单例都使用这个模式,而且它至少是非常显式的(这是python的)。

这是我自己对单例对象的实现。你所要做的就是布置课堂;为了获得单例,你必须使用Instance方法。这里有一个例子:

@Singleton
class Foo:
   def __init__(self):
       print 'Foo created'

f = Foo() # Error, this isn't how you get the instance of a singleton

f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance

print f is g # True

下面是代码:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Also, the decorated class cannot be
    inherited from. Other than that, there are no restrictions that apply
    to the decorated class.

    To get the singleton instance, use the `instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)

我真的不认为有这个需要,因为一个带有函数(而不是类)的模块可以很好地作为一个单例。它的所有变量都将绑定到模块,无论如何都不能重复实例化。

如果你确实希望使用一个类,在Python中没有办法创建私有类或私有构造函数,所以你不能防止多个实例化,只能通过使用API中的约定。我仍然会将方法放在模块中,并将模块视为单例模块。

模块方法工作得很好。如果我绝对需要一个单例,我更喜欢元类方法。

class Singleton(type):
    def __init__(cls, name, bases, dict):
        super(Singleton, cls).__init__(name, bases, dict)
        cls.instance = None 

    def __call__(cls,*args,**kw):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kw)
        return cls.instance

class MyClass(object):
    __metaclass__ = Singleton

你可以像这样重写__new__方法:

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()
    if (id(s1) == id(s2)):
        print "Same"
    else:
        print "Different"