0
点赞
收藏
分享

微信扫一扫

Python单例模式的简单写法

玉新行者 2022-08-23 阅读 62


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 条评论