Python如何实现单例模式?其他23种设计模式python如何实现?

 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  
原文地址:https://www.cnblogs.com/wht123/p/14217382.html