python如何实现单例模式?【面试题详解】

今天爱分享给大家带来python如何实现单例模式?【面试题详解】,希望能够帮助到大家。
第一种方法:使用装饰器



def singleton(cls):
    instances = {}
    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return wrapper
@singleton
class Foo(object):
    pass
foo1 = Foo()
foo2 = Foo()
print foo1 is foo2 #True

第二种方法:使用基类 New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例



class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,'_instance'):
            cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls._instance

class Foo(Singleton):
    pass

foo1 = Foo()
foo2 = Foo()

print foo1 is foo2 #True

原文链接:https://blog.itblood.com/4239.html,转载请注明出处。
0
欲望与权力v0.74 AI版[PC+安卓/3.21G/更新]Lust and Power [v0.74 Regular] [欧美SLG/汉化/动态]
欲望与权力v0.74 AI版[PC+安卓/3.21G/更新]Lust and Power [v0.74 Regular] [欧美SLG/汉化/动态]
10分钟前 有人购买 去瞅瞅看

站点公告

显示验证码
没有账号?注册  忘记密码?