python singleton
使用decorator的方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def singleton(cls): 2 instance = {} 3 def returnInstance(): 4 if cls not in instance: 5 instance[cls] = cls() 6 return instance[cls] 7 return returnInstance 8 9 @singleton 10 class MyClass(object): 11 def __init__(self): 12 self.x = 2 13 14 a = MyClass() 15 b = MyClass() 16 17 print a==b
值得注意的是:
第七行返回的是returnInstance而不是returnInstance()哦