python当中有很多方法都可以实现单例模式, 但利用__new__无疑是最推荐的方式.
代码如下:
class Demo:
is_instance = None
def __new__(cls, *args, **kwargs):
if cls.is_instance is None:
cls.is_instance = super(Demo, cls).__new__(cls)
return cls.is_instance
d1 = Demo()
d2 = Demo()
print(d1)
print(d2)
"""
<__main__.Demo object at 0x7fb2e775a7b8>
<__main__.Demo object at 0x7fb2e775a7b8>
"""