1. 组合:一个对象的属性值是另一个类的实例对象,alex.weapon是Weapon类的对象

class Dog:
    def __init__(self,name,aggr,hp,kind):
        self.name=name
        self.aggr=aggr
        self.hp=hp
        self.kind=kind

    def bite(self,person):
        person.hp-=self.aggr

class Person:
    def __init__(self,name,aggr,hp,sex):
        self.name=name
        self.aggr=aggr
        self.hp=hp
        self.sex=sex
        self.money=0

    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,stroke):  #武器放大招
        if self.njd>0:
            stroke.hp -= self.aggr*2
            self.njd -=1

alex=Person('alex',0.5,100,'不详')
jin=Dog('金老师',100,500,'teddy')
w=Weapon('打狗棒',100,3,998)

alex.money += 1000 #充值1000
#alex获取装备
alex.get_weapon(w)
print('alex获取的装备对象:',alex.weapon)
print('alex获取装备后总的血量:',alex.aggr)
print(alex.__dict__)

print('---------------------')
alex.attack(jin)   #alex打狗,狗的血掉了
print('alex打狗后,狗的血量:',jin.hp)

print('++++++++++++++++++++++')
alex.weapon.hand18(jin)  #alex用获取到的装备的大招打攻击狗
print('alex用大招攻击狗后,狗的血量:',jin.hp)
类的组合

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2021-11-18
  • 2021-11-18
  • 2021-11-18
  • 2021-11-18
  • 2021-11-18
  • 2021-12-16
猜你喜欢
  • 2022-01-02
  • 2021-07-01
  • 2021-07-21
  • 2021-11-18
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案