Python inheritance, python
1 # coding = UTF-8 2 class Fruit: # define a class 3 def _ init _ (self, color): 4 self. color = color 5 print ("fruit's color: '% s" % self. color) 6 7 def grow (self): 8 print ('grow... ') 9 10 class Apple (Fruit): # Apple inherits Fruit class 11 def _ init _ (self, color): 12 Fruit. _ init _ (self, color) # Apple must explicitly call the constructor of the parent class, which can be super (Apple, self ). _ init _ () calls the parent class 13 print ("apple's color: % s" % self. color) 14 15 class Banana (Fruit): 16 def _ init _ (self, color): 17 Fruit. _ init _ (self, color) 18 print ("banana's color: % s" % self. color) 19 20 def grow (self): # This grow method will overwrite the grow method 21 print ('banana grow... ') 22 23 if _ name __= = "_ main _": 24 apple = Apple ('red ') # Apple's _ init _ method calls the ___ init _ method of Fruit, so the information in the parent class is printed. (You can remove the print method of the parent class) then output the subclass information 25 apple. grow () # inherits from Fruit, so the information of the parent class is directly output 26 27 banana = Banana ('yellow') 28 banana. grow () # overwrite the information in the parent class