本节内容
1、没有重用父类代码
2、方式一:指名道姓(不依赖继承)
3、方式二:super() (依赖继承)
在子类派生出的新的方法中重用父类的方法,有两种实现方式
一、没有重用父类代码
class Hero: def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value-=self.aggresivity class Garen(Hero): camp='Demacia' def __init__(self,nickname,life_value,aggresivity,weapon): # self.nickname=nickname # self.life_value=life_value # self.aggresivity=aggresivity Hero.__init__(self,nickname,life_value,aggresivity) self.weapon=weapon def attack(self,enemy): Hero.attack(self,enemy) #指名道姓 print('from Garen Class') g=Garen('草丛伦',100,30,'金箍棒') print(g.__dict__)
方式一:指名道姓(不依赖继承)
1、代码
class Hero: def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value-=self.aggresivity class Garen(Hero): camp='Demacia' def attack(self,enemy): Hero.attack(self,enemy) #指名道姓 print('from Garen Class') class Riven(Hero): camp='Noxus' g=Garen('草丛伦',100,30) r=Riven('锐雯雯',80,50) print(r.life_value) g.attack(r) print(r.life_value)
2、打印结果
80 from Garen Class 50
方式二:super() (依赖继承)
1、代码
class Hero: def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value-=self.aggresivity class Garen(Hero): camp='Demacia' def attack(self,enemy): super(Garen,self).attack(enemy) #依赖继承 print('from Garen Class') class Riven(Hero): camp='Noxus' g=Garen('草丛伦',100,30) r=Riven('锐雯雯',80,50) g.attack(r) print(r.life_value)
super(Garen,self)就相当于实例本身 在python3中super()等同于super(
Garen,self)
2、打印结果
from Garen Class 50
3、总结
这两种方式的区别是:方式一是跟继承没有关系的,而方式二的super()是依赖于继承的,并且即使没有直接继承关系,super仍然会按照mro继续往后查找
#A没有继承B,但是A内super会基于C.mro()继续往后找 class A: def test(self): super().test() class B: def test(self): print('from B') class C(A,B): pass c=C() c.test() #打印结果:from B print(C.mro()) #[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]