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.py
PARENT implicit
PARENT implicit
PARENT override
CHILD override
PARENT altered
CHILD, BEFORE PARENT altered()
MUM, altered.
PARENT altered
CHILD, AFTER PARENT altered()