python 单例模式

class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,'_instance'):
            orig=super(Singleton,cls)
            cls._instance=orig.__new__(cls)
        return cls._instance
class MyClass(Singleton):
    def __init__(self,name):
        self.name=name
a=MyClass('a')                
b=MyClass('b')
print a.name, b.name    ##b b 
# ########### 单例类定义 ###########
class Foo(object):
 
    __instance = None
 
    @staticmethod
    def singleton():
        if Foo.__instance:
            return Foo.__instance
        else:
            Foo.__instance = Foo()
            return Foo.__instance
 
# ########### 获取实例 ###########
obj = Foo.singleton()
对于Python单例模式,创建对象时不能再直接使用:obj = Foo(),而应该调用特殊的方法:obj = Foo.singleton() 。


 
原文地址:https://www.cnblogs.com/howhy/p/7443877.html