
作用不同
1、__new__ 是用来创建类并返回这个类的实例,而 __init__ 只是将传入的参数来初始化该实例。
__init__() 初始化方法 和 __new__(),通过类创建对象时,自动触发执行。
概念不同
2、__new__() 创建对象时调用,会返回当前对象的一个实例
__init__() 创建完对象后调用,对当前对象的一些实例初始化,无返回值
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # __init__ 、 __new__
class Student(object):
def __init__(self, name, age):
print( '__init__() called' )
self.name = name
self.age = age
def __new__(cls, *args, **kwargs):
print( '__new__() called' )
print(cls, args, kwargs)
return super ().__new__(cls)
# ipython 测验
In [26]: s1 = Student( 'hui' , age=21)
__new__() called
<class '__main__.Student' > ( 'hui' ,) { 'age' : 21}
__init__() called
In [27]: s2 = Student( 'jack' , age=20)
__new__() called
<class '__main__.Student' > ( 'jack' ,) { 'age' : 20}
__init__() called
|
以上就是python中__init__ 和__new__的对比,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。