• 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() 。
    
    
    
     
  • 相关阅读:
    day06
    day05
    day04
    day03
    day02
    day01
    python-study-42
    OI 知识总览 算法篇 之 图论
    OI 知识总览 算法篇 之 基础算法
    [CSP2019-JX] 散步 解题报告
  • 原文地址:https://www.cnblogs.com/howhy/p/7443877.html
Copyright © 2020-2023  润新知