Python中__new__和__init__的区别与联系

__new__ 负责对象的创建而 __init__ 负责对象的初始化。

__new__:创建对象时调用,会返回当前对象的一个实例

__init__:创建完对象后调用,对当前对象的一些实例初始化,无返回值

1. 在类中,如果__new__和__init__同时存在,会优先调用__new__

1
2
3
4
5
6
7
class  ClsTest( object ):
     def  __init__( self ):
         print ( "init" )
     def  __new__( cls , * args,  * * kwargs):
         print ( "new" )
  
ClsTest()

输出:

1
new

2. 如果__new__返回一个对象的实例,会隐式调用__init__

代码实例:

1
2
3
4
5
6
7
8
class  ClsTest( object ):
     def  __init__( self ):
         print  ( "init" )
     def  __new__( cls , * args,  * * kwargs):
         print  ( "new %s" % cls )
         return  object .__new__( cls * args,  * * kwargs)
  
ClsTest()

输出:

1
2
new < class  '__main__.ClsTest' >
init

3. __new__方法会返回所构造的对象,__init__则不会。__init__无返回值。

1
2
3
4
5
6
7
class  ClsTest( object ):
      def  __init__( cls ):
              cls .x  =  2
              print  ( "init" )
              return  cls
  
ClsTest()

输出:

1
2
3
4
init
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
TypeError: __init__() should  return  None not  'ClsTest'

4. 若__new__没有正确返回当前类cls的实例,那__init__是不会被调用的,即使是父类的实例也不行

1
2
3
4
5
6
7
8
9
10
11
12
class  ClsTest1( object ):
     pass
  
class  ClsTest2(ClsTest1):
     def  __init__( self ):
         print  ( "init" )
     def  __new__( cls , * args,  * * kwargs):
         print  ( "new %s" % cls )
         return  object .__new__(ClsTest1,  * args,  * * kwargs)
  
b = ClsTest2()
print  ( type (b))

 输出:

1
2
new < class  '__main__.ClsTest2' >
< class  '__main__.ClsTest1' >

猜你喜欢

转载自www.cnblogs.com/cheyunhua/p/11351698.html