1 #使用__metaclass__(元类)的高级python用法
2 class Singleton2(type):
3 def __init__(cls, name, bases, dict):
4 super(Singleton2, cls).__init__(name, bases, dict)
5 cls._instance = None
6 def __call__(cls, *args, **kw):
7 if cls._instance is None:
8 cls._instance = super(Singleton2, cls).__call__(*args, **kw)
9 return cls._instance
10
11 class MyClass3(object):
12 __metaclass__ = Singleton2
13
14 one = MyClass3()
15 two = MyClass3()
16
17 two.a = 3
18 print one.a
19 #3
20 print id(one)
21 #31495472
22 print id(two)
23 #31495472
24 print one == two
25 #True
26 print one is two
27 #True
1 #使用装饰器(decorator),
2 #这是一种更pythonic,更elegant的方法,
3 #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
4 def singleton(cls, *args, **kw):
5 instances = {}
6 def _singleton():
7 if cls not in instances:
8 instances[cls] = cls(*args, **kw)
9 return instances[cls]
10 return _singleton
11
12 @singleton
13 class MyClass4(object):
14 a = 1
15 def __init__(self, x=0):
16 self.x = x
17
18 one = MyClass4()
19 two = MyClass4()
20
21 two.a = 3
22 print one.a
23 #3
24 print id(one)
25 #29660784
26 print id(two)
27 #29660784
28 print one == two
29 #True
30 print one is two
31 #True
32 one.x = 1
33 print one.x
34 #1
35 print two.x
36 #1
评论列表
文章目录