以下是組合的功能
#人狗大戰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,namen,aggr,njd,price): self.name = namen 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 alex = Person('alex',0.5,100,"不詳") jin = Dog('金老闆',100,500,'teddy') w = Weapon('打狗棒',100,3,998) #alex 裝備打狗棒alex.money += 1000alex.get_weapon(w) print(alex.aggr) alex.attack(jin) print(jin.hp) alex.weapon.hand18(jin) print(jin.hp) #組合 : 一個對象的屬性值是另外一個類的對象#
#alex.weapon是 weapon類的對象執行結果:
沒有留言:
張貼留言