__init__ method Section 8.3 Python class-depth analysis: Detailed construction methods and inheritance

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 )

The first 8.3 Jie Python class __init__ method -depth analysis: Detailed construction methods and inheritance

 

I. Introduction
on two describes the syntax and argument constructor, illustrating the construction method is a method creates an instance of the Python class executed first, and explain if the class does not override the constructor method, Python will give a default __init_ _method. The above description applies to the custom class does not define the situation from the parent class, if the custom class is derived from another custom class, what will happen?
Second, constructors and inheritance
in order to protect the relevant logical correctness, in the subclass overrides the constructor, you must call the superclass (inherited class) constructor, or it may not be properly initialize the object.
1. subclass at construction method for processing, there are two methods:
1> does not override the inherited constructor, this time directly subclass inherits the parent class constructor;
2> override the parent class constructor, sub class constructor where explicitly call parent class constructor without requiring the specific code location executed and may be at the beginning of the constructor of the subclass, the intermediate portion or end portion may be, mainly to see business logic, there is no requirement .
Both methods ensure the correctness of the subclass inherits the constructor of the parent class.

2. subclass display the three ways constructor call parent class
1> parent class name for the parent class constructor, this method requires attention, Self parameters must be passed to the parent class methods;.
. 2> Super () Parent class constructor calls this method does not require self argument can not pass, automatically imported from the Python;
.. 3> Super (subclass name, self) parent class constructor calls this method does not need to pass the self parameter.
The above three methods, the old ape recommend the use of a second, one is simple to use and does not need to give the name of the parent class or subclass name, do not need self parameter passing, the second is a simple program modification, if the parent class or subclass name modification without modifying the code. However, this method is only supported after Python3.

Third, the case
1. Case Note:
This section uses an inheritance case, the superclass is Vehicle (vehicle), sub-class car (car), the car only three instance variables: wheelcount (the number of wheels), power (power), the total mileage totaldistance, sub-categories according to different situations have different instance variable, an instance variable up to increase the fuel consumption per kilometer oilcostperkm (when using the error, back when the assignment is based on the assignment of hundred kilometers, it is noted). In order to focus the problem, only the definition of the constructor, the class definition in the superclass of the class as follows:

class Vehicle():
   def __init__(self,wheelcount, power):
       self.wheelcount,self.power,self.totaldistance = wheelcount,power,0

2. Case 1: The method of construction does not override subclass
1) subclass is defined as follows:

class Car(Vehicle):pass

At this point you should inherit the parent class constructor.
2) No write constructor, executed with no parameters defined instances, the system shall be given

car=Car()

3) the requirements defined by the parent class instance

car=Car(4,'汽油发动机') #带正确参数执行

4) Case screenshots:


 
5) Summary:
subclass inherits the parent class constructor, performs the direct execution instance constructor defined.

3. Case 2: Subclasses override without invoking the constructor subclass constructor parent class constructor
1) subclass is defined as follows:

class Car(Vehicle):  #子类重写构造方法但子类构造方法中不调用父类构造方法
    def __init__(self,wheelcount, power,oilcostperkm):
        self.oilcostperkm = oilcostperkm
        print("In Car __init__:oilcostperkm=",self.oilcostperkm)。

2) define instance

car=Car(4,'汽油发动机',10)

3) Examples of Data View

car.__dict__ #查看实例自定义属性,应该只有oilcostperkm
car.wheelcount #查看实例的    wheelcount,应报错

4) Case screenshots:


 
5) Summary:
A subclass overrides the constructor, if you call the parent class constructor is not displayed, it will not execute the relevant code of the parent class constructor.

4. Case 3: A subclass overrides the constructor and calling the parent class constructor
1) subclass is defined as follows:

class Car(Vehicle):  #子类重写构造方法但子类构造方法中不调用父类构造方法
    def __init__(self,wheelcount, power,oilcostperkm):
        self.oilcostperkm = oilcostperkm
        print("In Car __init__:oilcostperkm=",self.oilcostperkm)
        super().__init__(wheelcount, power) 

Constructor call parent class used in the present embodiment this is a call to the old ape preferred method, the method may further call the following two:

Vehicle.__init__(self,wheelcount, power)
super(Car,self).__init__(wheelcount, power)

2) define instance view data and

car=Car(4,'汽油发动机',10) #应该执行两个构造方法
car.__dict__ #查看实例自定义属性,应该wheelcount, power,oilcostperkm都有
car.wheelcount #查看实例的    wheelcount,应正常给出

3) Case Screenshot:


 
4) Summary: A subclass overrides the constructor, the display call the parent class constructor, instance variables are related to initialize properly.

This section details the combination of case in succession should realize how constructor of a subclass, the content is relatively simple but very important, please pay attention.
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/93513097