__new__ 单例
a.实例化类
实例化一个类时 1. 创建一个对象,调用__new__方法,如果没有会调用父类的__new__方法 2. 调用__init__方法 3. 返回对象的引用
class Dog(object): def __init__(self): print("---init方法---") def __new__(cls, *args, **kwargs): print("---new方法---") xtq = Dog() #---------结果--------- ---new方法---
b. 单例
class Dog(object): _instance = None _init_flag = False def __new__(cls, *args , **kwargs): #cls指向Dog if cls._instance == None: cls._instance = object.__new__(cls) return cls._instance else: return cls._instance def __init__(self,name): if Dog._init_flag == False: self.name = name Dog._init_flag = True a = Dog("旺财") print(a.name) b = Dog("啸天犬") print(b.name) #----------------结果----------------- 旺财 旺财