面向对象三大特性之二:继承 (Inheritance)
Python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。
1.0.1 继承写法
class Grandfather: def dance(self): pass class Father(Grandfather): #父类,或 基类 def football(self): pass def basketball(self): pass def somking(self): pass def drinking(self): pass def haircare(self): pass class Son(Father): #子类,或,派生类 def reading(self): pass obj = Son() obj.football()
最简单的练习题:
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): def s1(self): print('S.s1') obj = S() obj.s1() obj.f2()
1.0.2 继承重写:
如果 不想用父类里面的方法就可以把父类里面的方法,重新写一个。
执行的时候,就不会去找父类的方法了。
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): def s1(self): print('S.s1') def f2(self): #父类方法重写 print('S.f2') obj = S() obj.s1() #s1中的self是形参,此时代指obj obj.f2() #self永远指调用方法的调用者,就是obj
如果我们又想执行父类里面的方法,这里有二个方法:一个是super(),一个就是直接父类类名调用方法
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
super语法 :
super(type[, object-or-type])
type:子类名
bject-or-type:就是self
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): def s1(self): print('S.s1') def f2(self): super(S,self).f2() #找父类,然后执行父类的f2方法 F.f2(self) #也可以这样执行父类被重写的方法 print('S.f2')
super().xxx;super(child,self).xxx
方法法1:super(子类,self).父类中的方法(arg)
方法法2:父类名.父类中的方法(self. arg)
class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象 super(FooChild,self).__init__() print ('Child') def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')