码迷,mamicode.com
首页 > 编程语言 > 详细

python实现单例模式

时间:2018-02-25 19:20:20      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:说明   python   class   let   __new__   log   默认   nbsp   模式   

使用__new__方法可以实现单例模式:

class SingleTon(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, instance):
            cls.instance = object.__new__(cls, *args, **kw)
        return cls.instance

class TestClass(SingleTon):
    def __init__(self, num):
        self.num = num

test1 = TestClass(1)
test2 = TestClass(2)
print test1.num, test2.num
print id(test1), id(test2)

TestClass类实例化时,因为自身的__new__方法没有重写,默认会调用其父类,也就是SingleTon的__new__方法。而SingleTon的__new__方法重写为仅当自身没有instance属性时才会返回一个类实例,从而确保了仅生成1个实例。

上述代码运行后的结果:

2 2
48477016 48477016

两个实例的id相同,说明是同一个实例。但是其num值为2,是因为第二次实例化test2时,在__init__中将其num覆盖成了2。

 

python实现单例模式

标签:说明   python   class   let   __new__   log   默认   nbsp   模式   

原文地址:https://www.cnblogs.com/00986014w/p/8469925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!