Python單例模式的簡單寫法
class Singleton:
__instance = None
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls.__instance
# Test Singleton
s1 = Singleton()
s2 = Singleton()
print('s1 is s2', s1 is s2)
print('s1 == s2', s1 == s2)
程式的運作結果如下:
有關Python單例模式的其他寫法,見這篇文章