利用Python中的元类实现单例模式


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Singleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
# 如果是Python2
# super(Singleton,self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super().__call__(*args, **kwargs)
return self.__instance
else:
return self.__instance
class Spam(metaclass=Singleton):
# 如果是Python2
# __metaclass__=Singleton
def __init__(self):
print('Creating Spam')
if __name__ == '__main__':
a = Spam()
b = Spam()
print(a is b)
文章目录
|