魔法方法__new__()
__new__和__init__
的作用
class A(object): def __init__(self): print("这是 init 方法") def __new__(cls): print("这是 new 方法") return object.__new__(cls) A()
总结
-
__new__
至少要有一个参数cls,代表要实例化的类,此参数在实例化时由Python解释器自动提供 -
__new__
必须要有返回值,返回实例化出来的实例,这点在自己实现__new__
时要特别注意,可以return父类__new__
出来的实例,或者直接是object的__new__
出来的实例 -
__init__
有一个参数self,就是这个__new__
返回的实例,__init__
在__new__
的基础上可以完成一些其它初始化的动作,__init__
不需要返回值 -
我们可以将类比作制造商,
__new__
方法就是前期的原材料购买环节,__init__
方法就是在有原材料的基础上,加工,初始化商品环节
注意点
例子:
# 自定义一个人类 class Person(object): # 监听对象的创建过程 并返回创建成功的对象 def __new__(cls, *args, **kwargs): print("__new__") return object.__new__(cls) # 监听对象创建成功后 给对象添加属性并赋值 def __init__(self): print("__init__") self.money = 100 # 追踪对象的属性值变化 def __str__(self): print("__str__") return "钱:%d" % self.money # 监听对象销毁 def __del__(self): print("__del__") xm = Person() print(xm)