An analysis of Python inheritance

Source: Internet
Author: User
This article mainly introduces in-depth analysis of Python inheritance issues related materials, very good, interested friends to see together

Like the following code:

Class P1:def __init__ (self,a,b):p rint ("Init in P1") self.a1=aself.b1=bself.f1 () def F1 (self):p rint ("F1 in P1") Class C1 ( p1):d ef __init__ (self,a,b,c=2):p rint ("Init in C1") p1.__init__ (self,a,b) self.c1=cself.f1 () def F1 (self):p rint ("F1 in P2 ") Class C2 (C1):p assc=c2 (11,22) print (c.a1) print (C.B1) print (C.C1)

The code then runs the following results:

F:\python_code\test>python class_init.pyinit in C1init in P1f1 in P2f1 in p211222

With regard to the running of the code, I have the following questions, I will call to p1.__init__ () in the __init__ function of C1, and then each time it is run c1.f1 () function, no function running P1.f1 (), p1 running in F1 (), How is c1.f1 (). Why?

Cause Analysis:

p1.__init__ (SELF,A,B)

Self in this line of code is an object of C1. So the self that is passed to P1 inside is C1.

The above content described through the code to introduce the Python inheritance problem, we hope to help!

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.