元类实现单例模式
1 #coding=utf8 2 class Singleton(type): 3 _instances = {} 4 5 def __call__(cls, *args, **kwargs): 6 if cls not in cls._instances: 7 cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 8 return cls._instances[cls] 9 10 11 # Python2 12 class MyClass(object): 13 pass 14 __metaclass__ = Singleton 15 16 # Python3 17 # class MyClass(metaclass=Singleton): 18 # pass 19 20 m1=MyClass() 21 22 m2=MyClass() 23 24 print id(m1),id(m2)