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


当前回答

如果你想继续装饰(注释)类,创建一个单例装饰器(又名注释)是一种优雅的方式。然后将@singleton放在类定义之前。

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

其他回答

class Singleton(object[,...]):

    staticVar1 = None
    staticVar2 = None

    def __init__(self):
        if self.__class__.staticVar1==None :
            # create class instance variable for instantiation of class
            # assign class instance variable values to class static variables
        else:
            # assign class static variable values to class instance variables
class Singeltone(type):
    instances = dict()

    def __call__(cls, *args, **kwargs):
        if cls.__name__ not in Singeltone.instances:            
            Singeltone.instances[cls.__name__] = type.__call__(cls, *args, **kwargs)
        return Singeltone.instances[cls.__name__]


class Test(object):
    __metaclass__ = Singeltone


inst0 = Test()
inst1 = Test()
print(id(inst1) == id(inst0))

这是我自己对单例对象的实现。你所要做的就是布置课堂;为了获得单例,你必须使用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)

辛格尔顿同父异母的兄弟

我完全同意staale的观点,我在这里留下了一个创建单胎同父异母兄弟的例子:

class void:pass
a = void();
a.__class__ = Singleton

即使看起来不像单例,A现在也会报告为与单例属于同一个类。因此,使用复杂类的单例最终依赖于我们没有过多地干扰它们。

因此,我们可以使用更简单的东西,如变量或模块,以达到同样的效果。尽管如此,如果我们想要使用类来明确,并且因为在Python中类是一个对象,所以我们已经有了对象(不是实例,但它会像)。

class Singleton:
    def __new__(cls): raise AssertionError # Singletons can't have instances

如果我们尝试创建一个实例,我们会有一个很好的断言错误,我们可以在派生上存储静态成员,并在运行时对它们进行更改(我喜欢Python)。这个对象和其他同父异母的兄弟一样好(如果你愿意,你仍然可以创建它们),但是由于简单,它往往会运行得更快。

由ActiveState提供的Python实现的单例模式。

看起来窍门是把应该只有一个实例的类放在另一个类中。