python_面向对象——多继承
1.多继承
class Shenxian: def fly(self): print('神仙会飞~') class Monkey: def eat_peach(self): print('猴子喜欢吃桃子') # 继承多个类 class MongkeyKing(Shenxian,Monkey): def play_stick(self): print('孙悟空玩金箍棒') m = MongkeyKing() # 子类对象可以执行多个父类中的方法 m.play_stick() m.fly() m.eat_peach()
2.多继承顺序(按顺序从左到右继承)
class Shenxian: def fly(self): print('神仙会飞~') def fight(self): print('神仙打架') class Monkey: def eat_peach(self): print('猴子喜欢吃桃子') def fight(self): print('猴子打架') # 当多继承父类中同时有两个重名方法时,先继承左边父类中发方法(继承顺序从左到右) class MongkeyKing(Shenxian,Monkey): def play_stick(self): print('孙悟空玩金箍棒') m = MongkeyKing() m.fight()
3.查看多继续顺序
class Base: def fight(self): print('祖先在打架') class ShenxianBase(Base): def fight(self): print('神仙始祖们打架') class Shenxian(ShenxianBase): def fly(self): print('神仙会飞~') def fight(self): print('神仙打架') class MongekBase(Base): def eat(self): print('。。。') def fight(self): print('猿猴打架') class Monkey(MongekBase): def eat_peach(self): print('猴子喜欢吃桃子') def fight(self): print('猴子打架') class MongkeyKing(Monkey,Shenxian): def play_stick(self): print('孙悟空玩金箍棒') m = MongkeyKing() m.fight() # 显示类的多继承顺序 print(MongkeyKing.mro())
将类的继承顺序放在列表中顺序排放。