首页 > 编程语言 > 详细

python singleton

时间:2014-03-21 02:48:37      阅读:513      评论:0      收藏:0      [点我收藏+]

使用decorator的方式:

bubuko.com,布布扣
 1 def singleton(cls):
 2     instance = {}
 3     def returnInstance():
 4         if cls not in instance:
 5             instance[cls] = cls()
 6         return instance[cls]
 7     return returnInstance
 8 
 9 @singleton
10 class MyClass(object):
11     def __init__(self):
12         self.x = 2
13 
14 a = MyClass()
15 b = MyClass()
16 
17 print a==b
View Code

值得注意的是:

 第七行返回的是returnInstance而不是returnInstance()哦

python singleton,布布扣,bubuko.com

python singleton

原文:http://www.cnblogs.com/saobchj/p/3614672.html

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