只在第一次实例化对象时开辟一次对象的内存空间,以后所有由这个类实例化的对象都共用这个内存空间,并且后面的属性会覆盖之前的属性
class Foo:
__instance = None
def __init__(self, name):
self.name = name
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
p1 = Foo(1)
p2 = Foo(2)
print(p1.name)
print(p2.name)