在子类中重用父类的方法和属性
Posted huizaia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在子类中重用父类的方法和属性相关的知识,希望对你有一定的参考价值。
一、指名道姓法(不依赖继承,直接通过类调用方法和属性)
class Hero: def __init__(self, name, life, damage): self.name = name self.life = life self.damage = damage def attack(self, enemy): enemy.life -= self.damage class Garen(Hero): animal = ‘Garen‘ def attack(self, enemy): Hero.attack(self, enemy) # 指名道姓的方式 def __init__(self, name, life, damage, tree): Hero.__init__(self, name, life, damage) self.tree = tree st1 = Garen(‘盖伦‘, 100, 40, ‘大保健‘) class Riven(Hero): pass st2 = Riven(‘锐雯‘, 100, 50) print(st2.life) st1.attack(st2) print(st2.life) 输出结果: {‘name‘: ‘盖伦‘, ‘life‘: 100, ‘damage‘: 40, ‘tree‘: ‘大保健‘} 100 60
二、super()依赖继承
class Hero: def __init__(self, name, life, damage): self.name = name self.life = life self.damage = damage def attack(self, enemy): enemy.life -= self.damage class Garen(Hero): animal = ‘Garen‘ def attack(self, enemy): super(Garen, self).attack(enemy) #固定格式super(对象名,self) def __init__(self, name, life, damage, web): super().__init__(name, life, damage) #固定格式super() self.web = web st1 = Garen(‘盖伦‘, 100, 40, ‘大保健‘) print(st1.__dict__) class Riven(Hero): animal = ‘Noxus‘ st2 = Riven(‘锐雯‘, 100, 50) print(st2.life) st1.attack(st2) print(st2.life) 输出结果: {‘name‘: ‘盖伦‘, ‘life‘: 100, ‘damage‘: 40, ‘web‘: ‘大保健‘} 100 60
super找方法的顺序
class A: def f1(self): print(‘from A‘) super().f1() class B: def f1(self): print(‘from B‘) class C(A, B): pass print(C.mro()) a = C() a.f1() 输出结果: [<class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘__main__.B‘>, <class ‘object‘>] from A from B super是根据mro的顺序来找方法,先找A类,然后找到super时,在A顺序的基础上去找B的f1方法
以上是关于在子类中重用父类的方法和属性的主要内容,如果未能解决你的问题,请参考以下文章