单例模式:主要目的是确保某一个类只有一个实例存在
代码:
class A(): def __new__(self, *args, **kwargs): if not hasattr(self, 'name'): testname = super(A, self) self.name = testname.__new__(self) return self.name class B1(A): def __init__(self, name): self.name = name class B2(A): def __init__(self, name): self.name = name a = B1('zhangsan') print(a.name) # zhangsan b = B1('lisi') c = B2('wangwu') print(b.name) # lisi print(c.name) # wangwu b.name = 'zhaoliu' print(a.name) # zhaoliu print(b.name) # zhaoliu
结果: