码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2018-02-25 13:10:21      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:blog   通过   turn   运行   bsp   att   父类   有一个   直接   

程序运行期间此类只有一个实例存在,可以通过__new__创建实例时来做限制

 1 class Singleton(object):
 2     def __new__(cls, *args, **kwargs):
 3 #如果使用__new__创建类实例时,类中没有instance属性,则认为此类还没有创建过实例,
 4 #通过调用父类的__new__方法,super(Singleton, cls).__new__(cls)来创建实例
 5 #super(Singleton, cls).__new__(cls)等价于object.__new__(cls)
 6 #并把创建的实例,赋值给类属性instance
 7 #下次在创建实例时,发现类中包含类属性instance,则直接返回类属性instance
 8 #类属性instance的值为上次创建的实例
 9         if not hasattr(cls,"instance"):
10             cls.instance = super(Singleton, cls).__new__(cls)
11         return cls.instance
12 
13 s1 = Singleton()
14 s2 = Singleton()
15 print(s1 is s2)
16 #True

 

单例模式

标签:blog   通过   turn   运行   bsp   att   父类   有一个   直接   

原文地址:https://www.cnblogs.com/cx59244405/p/8468725.html

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