__new__(cls[,...])
__new__
方法在创建对象时,自动调用,起创建作用,创建完成,返回创建的对象
__new__
至少有一个参数cls
,代表实例化的类,此参数在实例化时由python解释器自动提供,也就是非特殊情况下,我们不用声明它__new__
必须有返回值,返回实例化出来的实例,这点在自己实现__new__
时要注意,可以return
父类__new__
出来的实例,或者直接是object的__new__
实例__init__
中的参数self
,就是这个__new__
返回的实例,__init__
在__new__
基础上可以完成一些其他初始化的动作,__init__
不需要返回值
__init__(self,...)
python中的说明:
-
Called after the instance has been created (by new()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an init() method, the derived class’s init() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().init([args…]).
-
Because new() and init() work together in constructing objects (new() to create it, and init() to customize it), no non-None value may be returned by init(); doing so will cause a TypeError to be raised at runtime.
__init__
在调用__new__
方法后自动调用,__init__(self)
中,默认有一参数名为self,如果在创建对象时传递了两个实参,那么__init__(self)
中除了self作为第一个参数外,还需要两个形参,例如:__init__(self,x,y)
__init__(self)
中的self参数,不需要开发者传递,python解释器会自动把当前的对象传递进去__init__
和__new__
区别是:__new__
用于创建对象,__init__
用于初始化对象,两者并起来,相当于C++/JAVA中的构造函数,创建并初始化
class A(object):
def __init__(self):
print("这是__init__方法,初始化对象")
def __new__(cls):
print("这是__new__方法,创建对象")
return object.__new__(cls)
# 创建一个对象a
a = A()
输出结果:
这是__new__方法,创建对象
这是__init__方法,初始化对象
所以当创建一个对象时,将先调用__new__
方法来创建对象,然后调用__init__
方法作初始化。这两个可以称作“构造”
__del__(self)
__del__(self)
在销毁一个对象时,默认调用,称为“析构”
class A(object):
def __init__(self,name):
self.name = name
print("这是__init__方法,初始化对象%s"%self.name)
def __new__(cls,name):
print("这是__new__方法,创建对象")
return object.__new__(cls)
def __del__(self):
print("%s对象被删除"%self.name)
# 创建一个对象a
a = A("a")
#del a
b = A("b")
c = A("c")