# -*- coding: UTF-8 -*- #super().__init__ 方法二调用父类 #super() 不仅可以再类的内部使用,也可以再类的外部使用 #super()内部使用: super().__init__(name,hp,aggr) #不需要传类名 #super()外部使用:super(Dog,gouzi).eat() #需要传类名字和对象名 class Animal: def __init__(self,name,hp,aggr): self.name = name self.hp = hp self.aggr = aggr def eat(self): self.hp += 100 print('%s 使用了金疮药,血量增加到 %s' % (self.name, self.hp)) class Dog(Animal): def __init__(self,name,hp,aggr,kind): super().__init__(name,hp,aggr) self.kind = kind #派生属性 def eat(self): Animal.eat(self) #如果既想使用父类原本的功能,也想实现新的功能,则需要在子类中调用父类 self.teeth = 2 self.hp += 100 print('%s 使用了金疮药,增加两颗牙齿' % (self.name)) def bite(self,person): person.hp -= self.aggr class Person(Animal): def __init__(self,name,hp,aggr,sex,money): Animal.__init__(self, name, hp, aggr) #super().__init__(name,hp,aggr) self.sex = sex #派生属性 self.money = 0 #派生属性 def eat(self): self.hp += 100 print('%s 使用了金疮药,血量增加到 %s' % (self.name, self.hp)) def attack(self,dog): #派生方法 dog.hp -= self.aggr def get_weapon(self,weapon): #派生方法 if self.money >= weapon.price: self.money -= weapon.price self.weapon = weapon self.aggr += weapon.aggr else: print('金币不足') class Weapon: def __init__(self,name,aggr,njd,price): self.name = name self.aggr = aggr self.njd = njd self.price = price def hand18(self,person): if self.njd > 0: person.hp -= self.aggr*2 self.njd -= 1 else: print("您的武器坏了") gouzi = Dog('哮天犬',999,200,'taidi') nezha = Person('哪吒',1999,300,'女',0) w = Weapon('打狗棒',200,3,998) super(Dog,gouzi).eat() #在父类和子类都有相同方法,仅执行父类 print(gouzi.hp) gouzi.eat() ##在父类和子类都有相同方法,父类和子类都执行 print(gouzi.hp)