首页 > 编程语言 > 详细

python实现单例模式

时间:2018-02-25 18:40:02      阅读:138      评论:0      收藏:0      [点我收藏+]

使用__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实现单例模式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!