在上一节中,我们重写了父类的方法,但是如果我们还想用这两个父类的方法,可按如下例子进行重写:
class Gun1(object): def __init__(self): self.length = 100 def shoot(self): print('bang1') class Gun2(object): def __init__(self): self.length = 200 def shoot(self): print('bang2') class Wuzi(Gun1,Gun2): def shoot(self): # 注意这里要先初始化自己,这样可以避免调用父类方法后再调用自己的方法时,还是父类的方法输出 self.__init__() print('bang3') def shoot1(self): # 调用父类方法时先初始化父类 Gun1.__init__(self) Gun1.shoot(self) def shoot2(self): # 同上 Gun2.__init__(self) Gun2.shoot(self) wuzi = Wuzi() wuzi.shoot() wuzi.shoot1() wuzi.shoot2()
此时输出为bang3,bang1,bang2
class Gun1(object): def __init__(self): self.length = 100 def shoot(self): print('bang1') class Gun2(object): def __init__(self): self.length = 200 def shoot(self): print('bang2') class Wuzi(Gun1,Gun2): def shoot(self): # 注意这里要先初始化自己,这样可以避免调用父类方法后再调用自己的方法时,还是父类的方法输出 self.__init__() print('bang3') def shoot1(self): # 调用父类方法时先初始化父类 Gun1.__init__(self) Gun1.shoot(self) def shoot2(self): # 同上 Gun2.__init__(self) Gun2.shoot(self) class XiaoWuzi(Wuzi): pass wuzi = XiaoWuzi() wuzi.shoot() wuzi.shoot1() wuzi.shoot2()
像XiaoWuzi这种继承了Wuzi(又继承自两个父类)这样的形式称为多层继承,它照样可以用最高父类(Gun1、Gun2)的方法
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句