Inheritance
Inheritance refers to the relationship between classes and classes, what is a "what" relationship, and one of the functions of inheritance is to solve code reuse problems
Inheritance is a way to create a new class, in Python, a new class can inherit one or more parent classes, and the parent class can be a base class or a superclass, and a new class is called a derived class or subclass
The inheritance of classes in Python is divided into: single inheritance and multiple inheritance
ClassParentClass1:#定义父类Passclass ParentClass2: #定义父类Passclass SubClass1(ParentClass1): #单继承 , the base class is ParentClass1, and the derived class is subclass Passclass SubClass2(ParentClass1, ParentClass2): #python支持多继承, separate multiple inherited class passes with commas
Inheritance and re-usability
In the process of developing a program, if we define a Class A and then want to create another class B, but most of the content of Class B is the same as Class A
It is not possible to write a class B from scratch, which uses the concept of class inheritance.
To create a new class B through inheritance, let B inherit all of the attributes (data attributes and function attributes) of a, a, a, to implement code reuse.
The implementation principle of inheritance
How python actually implements inheritance, for each class you define, Python calculates a list of method parsing orders (MRO), which is a simple linear sequential list of all base classes.
To implement inheritance, Python finds the base class from left to right on the MRO list until the first class that matches the property is found. The construction of this MRO list is implemented by a C3 linearization algorithm. We're not going to delve into the math of this algorithm, it's actually merging all of the parent's MRO lists and following three guidelines:
- Subclasses are checked before the parent class
- Multiple parent classes are checked according to their order in the list
- If there are two legitimate choices for the next class, select the first parent class
Calling a method of a parent class in a subclass
In the new method derived from the subclass, it is often necessary to reuse the methods of the parent class, we have two ways to implement
Mode one: Parent class name. Parent class Method ()
Way two: Super ()
The difference between the two ways is that the way one is not related to inheritance, and the super () mode two is dependent on inheritance, and even if there is no direct inheritance relationship, Super will continue to follow the MRO to find
< Span class= "token class-name" > < Span class= "token punctuation" > < Span class= "token punctuation" >
Python Foundation inheritance