Python中的单例设计模式与状态

时间:2015-10-20 17:50:41

标签: python python-3.x singleton state

我试图在Python中实现单例,在阅读this post后,我发现自己比以前更加困惑。有太多的答案,其中许多人已经获得了相当多的选票。现在问题可能不是我有一个单例,而是状态必须只初始化一次。我尝试了几个实现SingletonASingletonB,但我无法管理它。对于我真正的问题,__init__函数非常重,所以我只需要执行一次。这就是我到目前为止所做的:

class ClassA:

    def __init__(self):

        # some state
        print("Creating state in A")
        self.X = 1.
        self.Y = 2.

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


class ClassB:

    __shared_state = {}

    def __init__(self):

        if not bool(ClassB.__shared_state):

            # some state
            print("Creating state in B")
            self.X = 1.
            self.Y = 2.

        self.__dict__ = self.__shared_state


def singleton(cls):
    obj = cls()
    # Always return the same object
    cls.__new__ = staticmethod(lambda cls: obj)
    # Disable __init__
    try:
        del cls.__init__
    except AttributeError:
        pass
    return cls

@singleton
class SingletonB(ClassB):
    pass

if __name__ == "__main__":

    a1 = SingletonA()
    a2 = SingletonA()
    if (id(a1) == id(a2)):
        print("Same",a1.X, a1.Y)
    else:
        print("Different",a1.X, a1.Y)

    b1 = SingletonB()
    b2 = SingletonB()
    if (id(b1) == id(b2)):
        print("Same",b1.X, b1.Y)
    else:
        print("Different",b1.X, b1.Y)

现在正在打印:

$ python singleton.py 
Creating state in B
Creating state in B
Same 1.0 2.0
Creating state in A
Creating state in A
Same 1.0 2.0

指出事实上我确实有一个单例类,但我想避免创建状态。

2 个答案:

答案 0 :(得分:1)

这不起作用,因为__init__方法是在通过__new__创建对象后调用的。摘自Python Language Reference

  

如果__new__()返回cls的实例,那么将调用新实例的__init__()方法,如__init__(self[, ...]),其中self是新实例,其余参数是与传递给__new__()的相同。

您应该使用与__init__不同的特殊初始化方法,并在_instance创建时调用。

代码可以是(不需要父类,所以我省略了它):

class SingletonA:
    _instance = None
    def __init__(self):

        # some state
        print("Creating dummy state in SingletonA")

    def _init(self):

        # some state
        print("Creating state in SingletonA")
        self.X = 1.
        self.Y = 2.
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(SingletonA, cls).__new__(
                cls, *args, **kwargs)
            cls._instance._init()
        return cls._instance

但实际上,您可以在声明时简单地构建实例:

class SingletonA:
    def __init__(self):

        # some state
        print("Creating dummy state in SingletonA")

    def _init(self):

        # some state
        print("Creating state in A")
        self.X = 1.
        self.Y = 2.
    def __new__(cls, *args, **kwargs):
        return cls._instance

SingletonA._instance = super(SingletonA, SingletonA).__new__(SingletonA)
SingletonA._instance._init()

两种方式都会导致以下输出(对于SingletonA部分):

Creating state in A
Creating dummy state in SingletonA
Creating dummy state in SingletonA
('Same', 1.0, 2.0)

完全删除__init__方法会导致一次初始化。

注释版本可以是:

class ClassB:

    def __init__(self):

            # some state
            print("Creating state in B")
            self.X = 1.
            self.Y = 2.


def singleton(cls):
    obj = cls()
    # Always return the same object
    cls._instance = obj
    cls.__new__ = staticmethod(lambda cls: cls._instance)
    # Disable __init__
    cls.__init__ = (lambda self: None)
    return cls

@singleton
class SingletonB(ClassB):
    pass

只需将单例实例存储在类本身中

答案 1 :(得分:0)

如果我理解正确,这就是你所需要的:

# edited according to discussion in comments
class C:
    _shared_dict = None
    def __init__(self):
        if self._shared_dict is None:
            print("initializing")
            self.x = 1 
            self.y = 2 
            self.__class__._shared_dict = self.__dict__
        else:
            self.__dict__ = self._shared_dict

a=C()
b=C()

print(id(a), a.x, a.y)
print(id(b), b.x, b.y)

所有实例将共享相同的数据,此数据仅计算一次。

请注意,您可以在阅读时将共享数据称为self._shared_dict,但在写入时必须使用类属性self.__class__._shared_dict的全名。