A和B类都需要调用相同的方法
创建C类, 把相同的方法放到C类中
A和B继承 A(C) B(C)
A的对象和B的对象就可以直接调用C中的方法了
A和B中有相同的方法,一部分功能相同,还有不同的一部分
创建父类C,把相同的部分放到C类的方法中
在A、B中保留不同的部分,
然后分别在A、B中调用C类的方法即可
class Animo: # 父类
def __init__(self,name,hp,ad):
self.hp = hp
self.ad = ad
self.name = name
def eat(self):
self.hp += 10
print('%s增加了10点血'%self.name)
class Person(Animo):
def __init__(self,name,sex,hp,ad,job):
self.sex = sex
self.job = job
Animo.__init__(self,name,hp,ad) ## 主动添加self
def figth(self,dog):
dog.hp -= self.ad
print('%s打了%s一下,%s剩下了%s血' % (self.name,dog.name,dog.name,dog.hp))
class Dog(Animo):
def __init__(self,name,kind,hp,ad):
Animo.__init__(self,name,hp,ad) ## 主动添加self
self.kind = kind
def bite(self,persion):
persion.hp -= self.ad
print('%s咬了%s一下,%s剩下了%s血' % (self.name,persion.name,persion.name,persion.hp))
dog1 = Dog('二哈','哈士奇',30000,5)
alax = Person('alax','man',30000,300,'python')
alax.figth(dog1)
dog1.bite(alax)
alax.eat()
print(alax.hp)