在子类中派生出新的方法重用父类的方法,有两种实现方式
方式一:指名道姓(不依赖继承)
class Hero: def __init__(self,name,damage,zing): self.name = name self.damage = damage self.zing = zing def attack(self,enemy): enemy.zing -= self.damage class Yang(Hero): def attack(self,enemy): Hero.attack(self,enemy) #指名道姓的重用方法,可以在非继承的情况下使用 print("from Yang Class") pass class Lin(Hero): pass g1 = Yang(‘杨学伟‘,100,100) r1 = Lin(‘林书行‘,100,200) print(r1.zing) g1.attack(r1) print(r1.zing)
__init__方法的重用
方式二:super(依赖继承)
class Hero: def __init__(self,name,damage,zing): self.name = name self.damage = damage self.zing = zing def attack(self,enemy): enemy.zing -= self.damage class Yang(Hero): def attack(self,enemy): super(Yang,self).attack(enemy) #super(Yang,self)是一个对象 ,依赖于继承 print("from Yang Class") pass class Lin(Hero): pass g1 = Yang(‘杨学伟‘,100,100) r1 = Lin(‘林书行‘,100,200) print(r1.zing) g1.attack(r1) print(r1.zing)
class Hero: def __init__(self,name,damage,zing): self.name = name self.damage = damage self.zing = zing def attack(self,enemy): enemy.zing -= self.damage class Yang(Hero): def __init__(self,name,damage,zing,weapon): # self.name = name # self.damage = damage # self.zing = zing # Hero.__init__(self,name,damage,zing) super(Yang,self).__init__(name,damage,zing) #super是一个对象,所以再绑定方法的时候不用加第一个参数 self.weapon = weapon def attack(self,enemy): Hero.attack(self,enemy) #指名道姓的重用方法,可以在非继承的情况下使用 print("from Yang Class") pass g1 = Yang(‘杨学伟‘,100,100,‘圣剑‘) print(g1.__dict__)
super练习
#super class A: def f1(self): print("from A") super(A,self).f1() #super是基于C类的mro往后面寻找,而不A类的mro,所以可以去绑定B类的f1方法 class B: def f1(self): print("from B") class C(A,B): pass c = C() c.f1() # print(C.mro())