Differences and relations in __new__ Python and the __init__

Creating __new__ responsible for initializing objects and __init__ responsible for the object.

__new__: When you create an object called, it will return an instance of the current object

__init__: After creating the object invocation, some examples of the current object initialization, no return value

1. In the class, and if __new__ __init__ exist, it will give priority to calls __new__

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

Output:

1
new

2. If the returned instance of an object __new__, implicitly calling __init__

Code examples:

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()

Output:

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

 

3. __new__ method returns an object constructed, __ init__ does not. __init__ no return value.

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

Output:

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

4. If __new__ not return the correct instance of the current class cls, it is not __init__ is called, even the instance of the parent class is not OK

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))

 Output:

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

 

 

 

Guess you like

Origin www.cnblogs.com/cheyunhua/p/11351698.html