python 单例

方法1:使用装饰器(decorator)

def singleton(cls, *args, **kw):    
    instances = {}    
    def _singleton():    
        if cls not in instances:    
            instances[cls] = cls(*args, **kw)    
        return instances[cls]    
    return _singleton    
  
@singleton    
class MyClass(object):    
    a = 1    
    def __init__(self, x=0):    
        self.x = x    
    
one = MyClass()    
two = MyClass()    
    
two.a = 3    
print one.a    
#3    
print id(one)    
#29660784    
print id(two)    
#29660784    
print one == two    
#True    
print one is two    
#True    
one.x = 1    
print one.x    
#1    
print two.x  
3
35607384
35607384
True
True
1
1

方法2:使用metaclass元类来实现

class 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._instance    
    
class MyClass(object):    
    __metaclass__ = Singleton2    
    
one = MyClass()    
two = MyClass()    
    
two.a = 3    
print one.a    
#3    
print id(one)    
#31495472    
print id(two)    
#31495472    
print one == two    
#True    
print one is two    
3
47911488
47911488
True
True

方法3:通过共享属性来实现,所谓共享属性,最简单直观的方法就是通过dict属性指向同一个字典dict

class Borg(object):    
    _state = {}    
    def __new__(cls, *args, **kw):    
        ob = super(Borg, cls).__new__(cls, *args, **kw)    
        ob.__dict__ = cls._state    
        return ob    
    
class MyClass(Borg):    
    a = 1    
    
one = MyClass()    
two = MyClass()    
    
#one和two是两个不同的对象,id, ==, is对比结果可看出    
two.a = 3    
print one.a    
#3    
print id(one)    
#28873680    
print id(two)    
#28873712    
print one == two    
#False    
print one is two    
#False    
#但是one和two具有相同的(同一个__dict__属性),见:    
print id(one.__dict__)    
#30104000    
print id(two.__dict__)    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只...
    小爆虾丶阅读 207评论 0 0
  • 本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是...
    geekpy阅读 19,824评论 6 36
  • Python单例模式 单例模式 单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。...
    smile念殇阅读 450评论 0 4
  • 重写new方法 装饰器版本 import导入
    FangHao阅读 424评论 0 1
  • 今天开始新篇章:成长的烦恼。记录孩子们好玩的不好玩的烦恼。 今早,我爬起来做了老家一个小吃:炸糖糕。把面粉用开水烫...
    日出东方天刚晓阅读 247评论 1 0