1 # # 组合 2 # """定义:给一个类的对象封装一个属性,这个属性是另一个类的对象""" 3 # 4 # 5 # # 版本一: 添加武器:刀,枪,棍,棒,.... 6 # # 代码不合理,人物利用武器打人,你的动作发起者是人而不是武器 7 # class GameRole: 8 # 9 # def __init__(self, name, ad, hp): 10 # self.name = name 11 # self.ad = ad 12 # self.hp = hp 13 # 14 # def attack(self, p): 15 # p.hp = p.hp - self.ad 16 # print(f"{self.name}攻击了{p.name},{p.name}掉了{self.ad}血,还剩多少{p.hp}血") 17 # 18 # 19 # class Weapon: 20 # def __init__(self, name, ad): 21 # self.name = name 22 # self.ad = ad 23 # 24 # def fight(self, p1, p2): 25 # p2.hp = p2.hp - self.ad 26 # print(f"{p1.name}用{self.name}打了{p2.name},{p2.name}掉了{self.ad}血,还剩{p2.hp}血") 27 # 28 # 29 # p1 = GameRole('大阳哥', 20, 500) 30 # p2 = GameRole('虎哥', 50, 200) 31 # axe = Weapon('三板斧', 60) 32 # broadsword = Weapon('屠龙宝刀', 100) 33 # axe.fight(p1, p2) 34 # broadsword.fight(p2, p1) 35 36 # 版本二 37 # 组合 38 """定义:给一个类的对象封装一个属性,这个属性是另一个类的对象""" 39 # 给一个类的对象封装的一个属性封装另一个对象 称为组合 40 class Pa: 41 a = 0 42 def __init__(self, name): 43 self.name =name 44 45 46 class GameRole: 47 48 def __init__(self, name, ad, hp): 49 self.name = name 50 self.ad = ad 51 self.hp = hp 52 53 def attack(self, p): 54 p.hp = p.hp - self.ad 55 print(f"{self.name}攻击了{p.name},{p.name}掉了{self.ad}血,还剩多少{p.hp}血") 56 57 def armament_weapon(self, wea): 58 self.wea = wea 59 60 61 class Weapon: 62 def __init__(self, name, ad): 63 self.name = name 64 self.ad = ad 65 66 def fight(self, p1, p2): 67 p2.hp = p2.hp - self.ad 68 print(f"{p1.name}用{self.name}打了{p2.name},{p2.name}掉了{self.ad}血,还剩{p2.hp}血") 69 70 71 p1 = GameRole('大阳哥', 20, 500) 72 p2 = GameRole('虎哥', 50, 200) 73 axe = Weapon('三板斧', 60) 74 print(axe) 75 broadsword = Weapon('屠龙宝刀', 100) 76 p1.armament_weapon(axe) # 给大阳哥 装备了三板斧 77 # print(p1.wea) 78 # print(p1.wea.name) 79 # print(p1.wea.ad) 80 p1.wea.fight(p1, p2)