Inheritance of the Python_ class

Source: Internet
Author: User

1. The inheritance of the class and the relationship between the father, son and grandson in life, Python, if Class A inherits Class B, then class A is called a subclass, and Class B is called a parent class (also known as a base class).
2. The way of inheriting the class is divided into: single inheritance, multi-inheritance two kinds;
The single inheritance of a class means that a class inherits only one parent class B, as shown in:

The multiple inheritance of a class means that a class can inherit multiple parent classes, as shown in:

3. Order of class inheritance
If a subclass inherits one or more parent classes, is the subclass attribute any call? See examples, we define patient classes that inherit the hospital class and the Health Bureau class, question 1. The patient class and the hospital class have an enlisted method (Regpatien), at which point the subclass calls the method when it is called? 2. There are no addr properties in the subclass, and the addr attribute exists in the two parent class, and can the subclass call the Addr property when calling it normally? What is the Addr property of the parent class that is called if it can be called normally?
Question 1. See:

2.1. If the subclass inherits the parent class in the order of first hospital after Healthbureau, as shown in:

2.2. If the subclass inherits the parent class in the order of first Healthbureau after hospital, as shown in:


Summary: 1. When a subclass inherits from a parent class, the order in which the child class makes the property call is to find its own dictionary of properties, and then, in the order in which it inherits the parent class, to find the property dictionary of the parent class, in turn ; 2. Subclasses inherit the parent class, and when both the parent and child classes have the same properties, the subclass does not affect the properties of the parent class. Summed up is: In order to follow the inheritance of the property in turn, once the check is stopped; the properties of the subclass and the parent class are independent of each other; Subclasses can invoke the properties of the parent class, and vice versa;
The code block for this section is:

Class Hospital (): "Hospital-to-parent" addr = "Hospital Address: Wuxi Jiefang Road" depertment = ["Ultrasound section", "Radiology section", "Endoscopy section"] def __init__ (Self,name, Type,price): self.name = name Self.type = Type Self.price = Price def Regpatien (self): Prin        T ("--->> hospital is registering patients") class Healthbureau (): "Health Bureau class" addr = "Health Bureau class address: Wuxi city center Big Summer" def __init__ (self,heigh,size): Self.heigh =heigh self.size =size# class Patient (Hospital,healthbureau): #多继承, first Hospital after Healthbureauclass Pati ENT (healthbureau,hospital): #多继承, first Healthbureau after Hospital "Patient Class" Def __init__ (self,patientname,age,sex): self. Patientname = patientname Self.age = Age Self.sex =sex def regpatien (self): print ("--->> patient has Successful ") def tohispital (self): print ("%s go to%s check "% (Self.patientname,hospital.depertment[2])) #子类实例化patient1 = Patient ( "Li Ming", 24, "male") #父类Hospital实例化hospital = Hospital ("Wuxi People's Hospital", "Jiangsu province Wuxi People's Road", "three Armour") #子类实例调用regpatien方法patient1. Regpatien () #父类Hospital调用regpatien方法hospital. REgpatien () #子类实例调用addr方法print (PATIENT1.ADDR) 

? depth parsing class inheritance order
How to parse multi-tier inheritance relationships?
Multi-layer inheritance in Python2 and Python3 in different order, Python2 is the principle of depth first, Python3 is the principle of breadth first. The inheritance sequence is shown in:


Inheritance principle : How does Python actually implement the order of inheritance? For each class you define, Python calculates a list of method resolution orders (MRO), which is a simple, linear sequential list of all base classes.
To implement inheritance, Python looks for 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. The algorithm is actually merging all of the parent class's MRO lists and following three guidelines:
The ① subclass is checked by 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, you should select the first parent class;

For this reason we can directly use the subclass's MRO or MRO method to query its own inheritance order, as shown in:

4. Interface inheritance
From the above example, we can see that the inheritance of the class has 2 meanings: The subclass inherits the method of the base class and makes its own extension or change (reuse of the base class code); the second is: declares that a subclass is compatible with a base class, the parent class defines an interface class, the subclass inherits the interface class, and implements the methods defined in the
In practice, the first meaning of inheritance is often not recommended, it is less than the harm, the code will appear strong coupling, not conducive to the maintenance and expansion of the later, but the second meaning of the interface is very important, also known as ' interface inheritance '.
Interface inheritance is essentially: "A requirement to make an abstraction that specifies a compatible interface so that external callers do not need to know the specifics, and all objects that implement a particular interface are treated equally." "This is called normalization in the design of the program.
For example: Define a school's base class, schools have no courses, schools have different activities, but the kindergarten curriculum is simple letter recognition, counting, etc., and the university curriculum includes calculus, professional courses and so on. As shown, the above requirements are implemented through the inheritance of the interfaces:


If the course or activity function is not defined in the Kindergarten class or the college class, the instantiation is directly an error, as shown in:

So Interface inheritance is the name of the method that defines the subclass to implement in the base class (using @abc.abstractclassmethod to decorate the function, but it has no actual function), so that inheriting its subclass has to customize the function function, if the subclass does not have the function, the beginning of instantiation will be an error.
So if we know that some classes want to implement some function with the same name but not function, we can define a parent class, and then define the function that must be implemented in the parent class. This way the class inherits the parent class and avoids forgetting the function function that must be implemented, which is the method used to standardize the subclass. In fact, the base class does not have to be instantiated, because it is completely meaningless.
The code block for this section is:

Import Abcclass School (METACLASS=ABC. Abcmeta): "The base class of the school" @abc. Abstractclassmethod def course (self): "The Way school starts" pass @abc. Abstractclassme Thod def activity (self): "Method of Campus activity" Passclass Kindergarten (School): "Kindergarten Class" Def __init__ (self,name,a        Ddr,number): Self.name =name self.addr =addr self.number =number def course (self): "Lesson Function" Print ("%s",%self.name) def activity (self): "Tournament activity" print ("%s participated in the children's Dance Competition"%self.number) class C        Ollege (School): "Kindergarten Class" Def __init__ (self, name, addr, number): Self.name = name self.addr = addr Self.number = number # def course (self): # "course function" # Print ("%s has a course in calculus, advanced mathematics,"% self.name) def Activ ity (self): "Tournament activity" print ("%s participated in the College Oral Contest"%self.name) def Volunta (self): "Voluntary activity" print ("This is a volunteer activity" ) Kindergarten =kindergarten ("Millan Kindergarten", "Hangzhou Gongshu District", "kindergarten.activity () College =college" ("Zhejiang University", "Hangzhou Upper City", 65300) College.course () 

Inheritance of the Python_ class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.