Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
使用 __new__ 创建单例模式
class Singleton(object):
_instance = None
def __new__(cls, *args, **kswargs):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kswargs)
return cls._instance
class SingletonParent(object):
_instance = {}
def __new__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super(SingletonParent, cls).__new__(cls, *args, **kwargs)
return cls._instance[cls]
class A(SingletonParent):
class B(SingletonParent):
if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
assert id(s1) == id(s2)
a1 = A()
a2 = A()
assert id(a1) == id(a2)
b1 = B()
b2 = B()
assert id(b1) == id(b2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment