Python单例模式的简单写法

阅读 62

2022-08-23


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单例模式的简单写法_python

有关Python单例模式的其他写法,见这篇文章

​​http://python.jobbole.com/87294/​​

Python单例模式的简单写法_python_02


精彩评论(0)

0 0 举报