通过new方法,实现单例模式设计
class Singleton(object):__instance=Nonedef __init__(self):passdef __new__(cls, note):if cls.__instance is None:print("新建实例", note)# 以下3个语句,赋值号右侧 的效果完全一样 super()使用时一般不加参数;如果要加,第一个应该是当前的类cls.__instance=super().__new__(cls)# Singleton.__instance=super(Singleton, cls).__new__(cls) # 注意,此处__new__不传cls外的其它参数 python3语法# Singleton.__instance=object.__new__(cls)print(cls == Singleton)return cls.__instance# 注意:如果父类中,new方法下的cls换成类名Singleton,会导致子类继承后,redis类创建实例时,Singleton.__instance就已经存在了(也就是说,没有创建新的redis实例,仍然是db实例)# 子类和父类,本质上是两个类,所以子类创建实例的时候 cls==Singleton 的结果是False;父类创建实例时,cls==Singleton 的结果才是Trueclass MyDb(Singleton):def __init__(self, note):print('初始化', note)class MyRedis(Singleton):def __init__(self, note):print('初始化', note)db_one = MyDb('db____one')db_two = MyDb('db____two')redis_one = MyRedis("redis____one")redis_two = MyRedis("redis____two")print(id(db_one)) # 2565285375728print(id(db_two)) # 2565285375728print(db_one == db_two) # Trueprint(db_one is db_two) # Trueprint(id(redis_one)) # 2565285375728print(id(redis_two)) # 2565285375728print(redis_one == redis_two) # Trueprint(redis_one is redis_two) # True
执行结果
注意:
创建新的实例对象时,python3语法 object.new() 只传cls
