天天看点

Python单例模式的简单写法

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单例模式的其他写法,见这篇文章