我们首先得从__new__(cls[,…])的参数说说起,__new__方法的第一个参数是这个类,而其余的参数会在调用成功后全部传递给__init__方法初始化,
class A: pass class B(A): def __new__(cls): print("__new__方法被执行") return super().__new__(cls) # 注意这里,需要初始化 def __init__(self): print("__init__方法被执行") b = B()输出
__new__方法被执行 __init__方法被执行我们平时用__init__做初始化就好,什么时候用到__new__呢,看一下项目中是怎么用的,这里主要是涉及到了对象的操作,可以有效地防止反复创建对象,
class Logger: def __new__(cls, app_name: str, log_path: str, *args, **kwargs): if app_name not in cls.__instance: cls.__instance[app_name] = super().__new__(cls) return cls.__instance[app_name]报错输出
Traceback (most recent call last): File "/usr/local/pycharm-2020.1.1/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> AssertionError: 传入的日志路径必须为字符串,当前传入的路径为:2 ,类型为:<class 'int'>