一、概述

  Python中支持多继承,也就是一个子类可以继承多个父类/基类。当一个调用一个自身没有定义的属性时,它是按照何种顺序去父类中寻找的呢?尤其是当众多父类中都包含有同名的属性,这就涉及到新式类 和 经典类的区别。

 

二、多继承

 1 class Food(object):
 2 
 3     def __init__(self, name, color):
 4         self.name = name
 5         self.color = color
 6 
 7     def eatable(self):
 8         print("%s can be eaten." % self.name)
 9 
10     def appearance(self):
11         print('The color of the %s is %s.' % (self.name, self.color))
12 
13 
14 class Fruits(object):
15 
16     def __init__(self, name, nutrition):
17         self.name = name
18         self.nutrition = nutrition
19 
20     def info(self):
21         print("%s can supply much %s." % (self.name, self.nutrition))
22 
23 
24 class Salad(Fruits, Food):  # 继承多个父类
25 
26     def __init__(self, name, nutrition, color, tasty):
27         super(Salad, self).__init__(name, nutrition)
28         Food.__init__(self, name, color)
29         self.tasty = tasty
30 
31     def taste(self):
32         print("%s is a little %s." % (self.name, self.tasty))
33 
34 
35 obj = Salad('orange', 'VC', 'orange', 'sour')
36 
37 obj.eatable()
38 obj.appearance()
39 obj.info()
40 obj.taste()
View Code

相关文章: