在子类派生出新发方式中重用父类的方法,有两种实现方式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 __init__(self,nickname,life_value,aggresivity,weapon):# Hero.__init__(self,nickname,life_value,aggresivity)# self.weapon=weapon## def attack(self,enemy):# Hero.attack(self,enemy) #1,指名道姓# print(‘from Garen class‘)## class Riven(Hero):# camp=‘NOXUS‘### g=Garen(‘草丛伦‘,100,30,‘金箍棒‘)# r=Riven(‘锐雯雯‘,80,35)# print(g.__dict__)# print(r.life_value)# g.attack(r)# print(r.life_value) ‘‘‘# 2.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 attack(self,enemy): super(Garen,self).attack(enemy)#依赖继承 print(‘from Garen class‘) class Riven(Hero): camp=‘Noxus‘g=Garen(‘草丛伦‘,100,30)r=Riven(‘锐雯雯‘,80,35)g.attack(r)print(r.life_value)‘‘‘ ‘‘‘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 # self.weapon = weapon # Hero.__init__(self,nickname,life_value,aggresivity) #super(Garen,self).__init__(nickname,life_value,aggresivity) #依赖继承
super().__init__(nickname,life_value,aggresivity) #依赖继承(Python3) self.weapon=weapon def attack(self,enemy): Hero.attack(self,enemy) #指名道姓重用 print(‘from Garen class‘) class Riven(Hero): camp=‘NOXUS‘ g=Garen(‘草丛伦‘,100,30,‘金箍棒‘)r=Riven(‘锐雯雯‘,80,35)print(g.__dict__)print(r.life_value)g.attack(r)print(r.life_value)‘‘‘那么super是怎么实现在父类中查找的呢一个小验证方法: class A: def f1(self): print(‘from A‘) super().f1() class B: def f1(self): print(‘from B‘) class C(A,B): passprint(C.mro()) c=C()c.f1()返回:
[<class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘__main__.B‘>, <class ‘object‘>] #C.mro() c的查找顺序,新式类(python3特有)
from A
from B
以上看出父类重用,是子类以mro()的顺序查找的,不论父类之间有没有继承关系
PS mro()‘老子才不管你老子是谁,老子只按老子的查找顺序查找‘
原文地址:https://www.cnblogs.com/sunny666/p/9641022.html
时间: 2024-10-11 01:04:24