组合: 给一个类的对象封装一个属性,这个属性是另一个类的对象.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class GameRole: def __init__( self , name, ad, hp): self .name = name self .ad = ad self .hp = hp def attack( self ,p): p.hp = p.hp - self .ad print ( '%s 攻击 %s,%s 掉了%s血,还剩%s血' % ( self .name,p.name,p.name, self .ad,p.hp)) def armament_weapon( self ,wea): self .wea = wea class Weapon: def __init__( self ,name,ad): self .name = name self .ad = ad def fight( self ,p1,p2): p2.hp = p2.hp - self .ad print ( '%s 用%s打了%s,%s 掉了%s血,还剩%s血' \ % (p1.name, self .name,p2.name,p2.name, self .ad,p2.hp))<br><br>p1 = GameRole( '大阳哥' , 20 , 500 ) #给对象封装属性<br>p2 = GameRole('印度阿宁',50,200)<br>axe = Weapon('三板斧',60)<br>broadsword = Weapon('屠龙宝刀',100)p1.armament_weapon(axe) #给p1这个属性封装axe这个对象,就可以调用axe里的功能.<br>p1.wea.fight(p1,p2)可以直接调用Weapon这个类里的函数,里面传了参数,因为wea装了axe = Weapon('三板斧',60).armament_weapon |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步