In-depth analysis of python inheritance and python inheritance

Source: Internet
Author: User

In-depth analysis of python inheritance and python inheritance

The following code is available:

Class p1: def _ init _ (self, a, B): print ("init in p1") self. a1 = aself. b1 = bself. f1 () def f1 (self): print ("f1 in p1") class c1 (p1): def _ init _ (self, a, B, c = 2): print ("init in c1") p1. _ init _ (self, a, B) self. c1 = cself. f1 () def f1 (self): print ("f1 in p2") class c2 (c1): passc = c2 (11,22) print (c. a1) print (c. b1) print (c. c1)

The code execution result is as follows:

F: \ python_code \ test> python class_init.pyinit in c1init in p1f1 in p2f1 in p238622

Regarding the code running process, I have the following questions: In the _ init _ function of c1, I will call p1. _ init __(), then, the c1.f1 () function is run every time, and the p1.f1 () function is not run. The f1 () function running on p1 is also c1.f1 (). Why?

Cause analysis:

P1. _ init _ (self, a, B)

In this line of code, self is the object of c1. So the self passed to p1 is c1.

The above content introduces python inheritance through code, and I hope it will help you!

Related Article

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.