单例模式元类

元类实现单例模式

 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)

 

posted @ 2018-01-18 17:30  北风之神0509  阅读(233)  评论(0编辑  收藏  举报