__new__ methods and constructors Relations Section 8.7 Python class-depth analysis: __ new__ method the results of the impact of the case on the __init__ Detailed

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

I. Introduction The
previous section describes a method and a construction method __new__ class, and the sequence relationship between the two analyzes performed. __new__ method before __init__ method of execution, after new__ __ execution method returns an instance of the object, that is to say before the implementation of the method __new__ instance did not create, parameter self constructor is passed after the last execution method __new__ examples. If that method does not __new__ instance of an object returned would happen then?
Second, the case illustrates
this section old ape ready to verify two situations:
1, __new__ not overridden method returns an instance of what would happen?
2, rewriting method instance calls __new__ parent class, cls class name when the instance is created, but if you do not pass one other class would happen?
This section defines two classes, a class Cir circle, a rectangle Rect class, class has attributes Cir RADIUS (radius), there are two attributes Rect len (length) and width (W).

Third, the normal codes
following code defines the class codes to the normal of these two classes defined and the statement is executed example:

class Rect():
   def __new__(cls,len,width):
       print("In Rect __new__,cls的值为:",cls)
       inst = super().__new__(cls)  
       print("Rect.__new__返回值:",inst)
       return inst

   def __init__(self,len,width):
       print("In Rect init,self的值为:",self,", len,width的值为:",(len,width))
       self.len,self.width = len,width          
   
class Cir():
   def __new__(cls,radius):
       print("In Cir __new__,cls的值为:",cls)
       inst = super().__new__(cls)  
       print("Cir.__new__返回值:",inst)
       return inst

   def __init__(self,radius):
       print("In Cir init,self的值为:",self,", radius的值为:",radius)
       self.radius = radius

 cir=Cir(10)
     rect=Rect(5,4)

Related shots are as follows:
Here Insert Picture Description
four, Cir analog class __new__ method without return value
1, Cir circle defined class, and no value is returned __new__ Method:

class Cir():
   def  __new__(cls,radius):
       print("In Cir __new__,cls的值为:",cls)
       inst = super().__new__(cls)  
       print("Cir.__new__返回值:",inst)
       #return inst  #不返回实例

   def __init__(self,radius):
       print("In Cir init,self的值为:",self,", radius的值为:",radius)
           self.radius = radius

2, execution instance and attributes defined view (interactive mode execution)

cir=Cir(10)#从返回信息来看只执行了__new__方法,没有执行构造方法
type(cir) #类型为'NoneType',不是我们期望的类型
cir.__dict__ #报AttributeError

3, the screenshot
Here Insert Picture Description
4, when not overridden __new__ method returns an instance, the constructor is not performed, the object is returned NoneType, inaccessible.
V. Analog Cir __new__ method does not return the class instance, but other types, such as the case return integer
no detailed explanation, the code directly on the theme:
Here Insert Picture Description
CONCLUSION: constructor does not perform, creating an instance of the method into a __new__ return value.
Six analog Cir __new__ class parent class method is invoked method, passing the class name of the class where Rect

  1. code show as below:
class Rect():
   def __new__(cls,len,width=0):
       print("In Rect __new__,cls的值为:",cls)
       inst = super().__new__(cls)
       print("Rect.__new__返回值:",inst)
       return inst

   def __init__(self,len,width=0):
       print("In Rect init,self的值为:",self,", len,width的值为:",(len,width))
       self.len,self.width = len,width

class Cir():
   def __new__(cls,radius):
       print("In Cir __new__,cls的值为:",cls)
       inst = super().__new__(Rect) #传递参数变成 Rect类
       print("Cir.__new__返回值:",inst)
       return inst

   def __init__(self,radius):
       print("In Cir init,self的值为:",self,", radius的值为:",radius)
       self.radius = radius

	cir=Cir(10)
	cir.__dict__
	cir.__init__(10)
	type(cir)
  1. Screenshot execution:
    Here Insert Picture Description
  2. Case Studies
  1. After calling the parent class object class name becomes Rect, two class constructors are not executed;
  2. Examples of type Rect becomes returned, but there is no Rect class constructor is executed, there is no instance variables initialized;
  3. Can call the constructor returns a single instance in the code, but is configured of Rect types of execution, since the two are not the same class constructor parameter, the present embodiment provides the default value configured by the Rect methods to resolve, if not available, it will be reported "TypeError: the init () 1 Missing required Positional argument: 'width'."
    CONCLUSIONS
    Through the above cases verification, we can draw the following conclusions:
  1. If __new__ method of rewriting, no value is returned, the constructor does not perform __init__, defined instance of an object type is abnormal 'NoneType', inaccessible;

  2. If __new__ method of rewriting, not instances of the class itself, but other types of return, the constructor does not perform __init__, instance of an object is defined by the return value, according to the value corresponding to the type of access ;

  3. If the __new__ overridden method, call the parent class __new__ method, the parameters passed to the other alternative examples are cls custom class or other classes, the constructor does not perform __init__ returned other custom object classes, custom attributes are associated undefined.
    Thus, if the returned data is not correctly __new__, the constructor will not be executed, the finally generated instance, a value consistent with the same type of return value, can be accessed by a corresponding type.

    This section old ape verified __new__ method returns affect the value of the constructor and generating instances, the correct method is very important to perform __new__ described, these anomalies are not necessarily wrong, there may in certain circumstances this time will be used for special purposes, described later advanced knowledge metaclass.
    Old ape Python ( https://blog.csdn.net/LaoYuanPython) series of articles for the gradual introduction summary of the old ape learning Python learning experience, which helps no contact with Python programmers can easily enter Python world.
    Welcome criticism, thank you attention!

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/93643829