例子
class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1 one = MyClass() two = MyClass() print(one == two) print(one is two) print(id(one), id(two))
输出
True True 499807697384 499807697384 [Program finished]
例子
class test(object): _a=None def __init__(self): self.b=2 def __new__(cls,*args,**kargs): if(not cls._a): cls._a=super(test,cls).__new__(cls,*args,**kargs) return cls._a x=test() print(x) print(x.b) y=test() print(y) print(y.b)
输出
<__main__.test object at 0x716e0fb9e8> 2 <__main__.test object at 0x716e0fb9e8> 2 [Program finished]