首页 > 代码库 > Python单例模式
Python单例模式
#-*- encoding=utf-8 -*-class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, ‘_instance‘): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instanceclass MyClass(Singleton): a = 1one = MyClass()two = MyClass()two.a = 3print one.a#3#one和two完全相同,可以用id(), ==, is检测print id(one)print id(two)print one == two#Trueprint one is two#Trueclass Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return obclass MyClass2(Borg): a = 1one = MyClass2()two = MyClass2()two.a = 3print one.aprint id(one)print id(two)print one == twoprint one is twoclass Singleton2(type): def __init__(cls, name, bases, dict): super(Singleton2, cls).__init__(name, bases, dict) cls._instance = None def __call__(cls, *args, **kw): if cls._instance is None: cls._instance = super(Singleton2, cls).__call__(*args, **kw) return cls._instanceclass MyClass3(object): __metaclass__ = Singleton2one = MyClass3()two = MyClass3()two.a = 3print one.a#3print id(one)#31495472print id(two)#31495472print one == two#Trueprint one is two#Truedef singleton(cls, *args, **kw): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return _singleton@singletonclass MyClass4(object): a = 1 def __init__(self, x=0): self.x = xone = MyClass4()two = MyClass4()two.a = 3print one.a#3print id(one)#29660784print id(two)#29660784print one == two#Trueprint one is two#Trueone.x = 1print one.x#1print two.x#1
class3使用了元类。
class4使用了美妙的decorator。
Python单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。