博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 单例模式
阅读量:4659 次
发布时间:2019-06-09

本文共 780 字,大约阅读时间需要 2 分钟。

class Singleton(object):    def __new__(cls,*args,**kwargs):        if not hasattr(cls,'_instance'):            orig=super(Singleton,cls)            cls._instance=orig.__new__(cls)        return cls._instanceclass MyClass(Singleton):    def __init__(self,name):        self.name=namea=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

你可能感兴趣的文章