Python Object-oriented inheritance

Source: Internet
Author: User

Objective:

Inheritance is one of the three main features of object-oriented, so you should pay attention to 3 points for inheritance.

first, the basic search

If the subclass inherits the parent class, the child class instantiates the object, and no methods and properties are found to the parent class.

class # Parent Class    def F1 (self):         Print ('F1') class # sub-class    Pass obj=sub ()      # If the subclass inherits the parent class, the child class instantiates the object, no methods and properties go to the parent class bar ()obj.f1 ()
View Code

Second, multiple inheritance lookup

The classes in Python support multiple inheritance, so what is the subclass's order to find the inherited parent class? This problem does not exist in Java and C # because they do not support multiple inheritance at all;

1, the class in Python3 belongs to the new class, the first find rule is breadth first (looking from left to right)

classD (B):defF1 (self):Print('d.f1')classE (C):defF1 (self):Print('e.f1')classF (d,e):Passobj=f ()#Class F Inherits Class D, breadth first (from left to right, first to find the F1 method for Class D)obj.f1 ()#Execution Result D.f1
View Code

2, corresponding to the new class of Python3, if the parent class still does not have the child class instance wants, will look for the parent class's parent class, the depth finds the last ancestor class; (1 left)

classA (object):defF1 (self):Print('a.f1')classB (A):#Class B also has no, F object will not go to class A, continue breadth find to Class E    defF2 (self):Print('b.f1')classC (A):defF1 (self):Print('c.f1')classD (B):defF2 (self):Print('d.f1')classE (C):defF1 (self):Print('e.f1')classF (d,e):Passobj=f ()#Class F Inherits Class D, breadth first (looking from left to right, first finding Class D, Class D without F1 method, looking up D's parent class Class B)obj.f1 ()#Execution Result E.f1
View Code

third, who is self?

Python Object-oriented inheritance

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.