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)
标签:p2,p1,name,组合,self,hp,ad 来源: https://www.cnblogs.com/yuxin2021/p/15511552.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。