标签:需要 from 并且 val style 实现 test lib 关系
在子类派生出的新的方法中重用父类的方法,有两种实现方式
一、指名道姓(不依赖继承)
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 Libai(Hero): camp = "Tangchao" 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) # 指名道姓,有几个参数就需要传几个参数 print("from Libai Class") class Huamulan(Hero): camp = "Changcheng" l1 = Libai("进一步",100,60,"剑")
二、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 Libai(Hero): camp = "Tangchao" def __init__(self,nickname,life_value,aggresivity,weapon): #Hero.__init__(self,nickname,life_value,aggresivity) #super(Libai,self).__init__(nickname,life_value,aggresivity) # python2的写法 super().__init__(nickname,life_value,aggresivity) # python3的写法 self.weapon = weapon def attack(self,enemy): super(Libai,self).attack(enemy) # 依赖继承 super(Libai,self)是指对象,.attack是调用对象的方法 print("from Libai Class") class Huamulan(Hero): camp = "Changcheng" l1 = Libai("进一步",100,60,"剑")
这两种方式的区别是:方式一是跟继承没有关系的,而方式二的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‘>]
标签:需要 from 并且 val style 实现 test lib 关系
原文地址:https://www.cnblogs.com/nanjo4373977/p/12176028.html