1. python中的繼承
class Parent(object): def override(self): print "PARENT override()" def implicit(self): print "PARENT implicit()" def altered(self): print "PARENT altered()"class Child(Parent): def override(self): print "CHILD override()" def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() #注意super的用法!!!! print "CHILD, AFTER PARENT altered()"dad = Parent()son = Child()dad.implicit()son.implicit()dad.override()son.override()dad.altered()son.altered()
python可以多重繼承,即一個class可以有多個父類。
class Son(Dad, Mum): pass
這時,當調用super(Son, self).***()的時候,會看Dad裡有沒有這個方法,如果有,就不調用Mum裡的了,如果沒有,才查看Mum裡有沒有,看下面的代碼:
class Parent(object): def override(self): print "PARENT override" def implicit(self): print "PARENT implicit" def altered(self): print "PARENT altered"class Mum(object): def altered1(self): print "MUM, altered."class Child(Mum, Parent): def override(self): print "CHILD override" def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered1() super(Child, self).altered() print "CHILD, AFTER PARENT altered()"dad = Parent()son = Child()dad.implicit()son.implicit()dad.override()son.override()dad.altered()son.altered()
輸出結果:
E:\SkyDrive\python\the hard way to learn python>python ex44_4.pyPARENT implicitPARENT implicitPARENT overrideCHILD overridePARENT alteredCHILD, BEFORE PARENT altered()MUM, altered.PARENT alteredCHILD, AFTER PARENT altered()