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!