1 #coding=utf-8
2 class Fruit:#定义一个类
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继承Fruit类
11 def __init__(self,color):
12 Fruit.__init__(self,color)#Apple必须显式调用父类的构造函数,可以super(Apple,self).__init__()调用父类
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):#此grow方法会覆盖Fruit中的grow方法
21 print('banana grow...')
22
23 if __name__=="__main__":
24 apple=Apple('red')#Apple的__init__方法调用了Fruit的___init__方法,所以会打印父类中的信息,(可以将父类的print方法去掉)再输出子类的信息
25 apple.grow()#继承自Fruit,所以直接输出父类的信息
26
27 banana=Banana('yellow')
28 banana.grow()#覆盖父类中信息