现在的位置: 首页 > 综合 > 正文

关于python的单例模式

2013年02月27日 ⁄ 综合 ⁄ 共 708字 ⁄ 字号 评论关闭

原文地址:http://blog.csdn.net/ghostfromheaven/article/details/7671914

如果你真的想使用其他编程语言中类似的“单例模式”,你需要看:

http://blog.csdn.net/ghostfromheaven/article/details/7671853

http://ghostfromheaven.iteye.com/blog/1562618

但是,我要问的是,Python真的需要单例模式吗?我指像其他编程语言中的单例模式。

答案是:不需要!

因为,Python有模块(module),最pythonic的单例典范。

模块在在一个应用程序中只有一份,它本身就是单例的,将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可!

http://stackoverflow.com/a/31887/1447185

转载时注:

如果确实想做成类而不是模块,下面这种方式可能是与其他语言中定义单例模式最相近,最容易理解的方法:

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"

抱歉!评论已关闭.