# -*- coding:utf-8 -*- # 父类中没有的属性、在子类中出现,叫做派生属性 # 父类中没有的方法、在子类中出现,叫做派生方法 # 只要是子类的对象调用方法,子类和父类中都有的话,一定用子类的,子类中没有才找父类,如果父类也没有则报错 # 如果还想用父类的、则需要单独调用,需要传self参数 # Animal.__init__(self,name,hp,aggr) #方法一调用父类 # super().__init__ 方法二调用父类 # super() 不仅可以再类的内部使用,也可以再类的外部使用 # super()内部使用: super().__init__(name,hp,aggr) #不需要传类名 # super()外部使用:super(Dog,gouzi).eat() #需要传类名字和对象名 # 正常代码中 单继承 == 减少了代码的重复 # 继承表达的是一种 子类是父类的关系 # 使用组合和继承的关键点、需要看是==是的关系 = 还是有的关系 # 1、老师有生日[组合]、不能说老师是生日 、教授是老师[继承] # 2、查看是否有相同代码、相同代码即用继承 #方法一调用父类 Animal.__init__(self,name,hp,aggr) 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): Animal.__init__(self,name,hp,aggr) #Animal.__init__(self,name,hp,aggr) #方法一调用父类 self.kind = kind #派生属性 def eat(self): Animal.eat(self) #如果既想使用父类原本的功能,也想实现新的功能,则需要在子类中调用父类 self.teeth = 2 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) 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) print(gouzi.__dict__) w = Weapon('打狗棒',200,3,998) gouzi.eat() nezha.eat() print(gouzi.hp) print(nezha.hp) print(gouzi.__dict__)