python的继承
继承是面向对象的重要特征之一,继承是两个类或者多个类之间的父子关系,子进程继承了父进程的所有公有实例变量和方法。继承实现了代码的重用。重用已经存在的数据和行为,减少代码的重新编写,python在类名后用一对圆括号表示继承关系, 括号中的类表示父类,如果父类定义了__init__方法,则子类必须显示地调用父类的__init__方法,如果子类需要扩展父类的行为,可以添加__init__方法的参数。
单继承:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Eric.yue 4 5 class Fruit(object): 6 def __init__(self, color): 7 self.color = color 8 print "fruit's color: %s" % self.color 9 10 def grow(self): 11 print "grow..." 12 13 class Apple(Fruit): 14 def __init__(self,color): 15 Fruit.__init__(self,color) #继承父类的构造方法 16 print "apple's color: %s" % self.color 17 18 19 class Banana(Fruit): # 继承了父类 20 def __init__(self, color): # 显示调用父类的__init__方法 21 Fruit.__init__(self, color) 22 print "banana's color:%s" % self.color 23 24 def grow(self): # 覆盖了父类的grow方法 25 print "banana grow..." 26 27 if __name__ == "__main__": 28 apple = Apple("red") 29 apple.grow() 30 print '--------' 31 banana = Banana("yellow") 32 banana.grow() 33 34 ''' 35 输出结果: 36 fruit's color: red 37 apple's color: red 38 grow... 39 -------- 40 fruit's color: yellow 41 banana's color:yellow 42 banana grow... 43 '''
多继承:
1 class Person1(object): 2 def __init__(self): 3 self.name = 'person1 name' 4 5 def running(self): 6 print 'person1 is running' 7 8 9 class Person2(object): 10 def __init__(self): 11 pass 12 13 def swimming(self): 14 print 'person2 is swimming' 15 16 17 class Mike(Person1,Person2): 18 def __init__(self): 19 Person1.__init__(self) 20 #self.name = 'Mike name' 将覆盖person1中的name 21 22 m = Mike() 23 print m.name 24 m.running() 25 m.swimming() 26 27 ''' 28 输出结果 29 Mike name 30 person1 is running 31 person2 is swimming 32 '''