python中类和类的组合,依赖,关联关系
组合关系:将一个对象封装到另一个对象的属性中
# 组合的好处: # 1,代码更合理。 # 2, 类与类之间的耦合性增强。 class GameRole(object): def __init__(self, n, a, h): self.name = n self.ad = a self.hp = h def attack(self, obj): obj.hp -= self.ad print('%s攻击%s,%s掉了%s血,还剩%s血' % (self.name, obj.name, obj.name, self.ad, obj.hp)) # 把一个对象的属性里封装另一个对象,叫做组合 def equip_weapon(self, wea): self.wea = wea class Weapon: def __init__(self, name, ad): self.name = name self.ad = ad def weapon_attack(self, p1, p2): p2.hp = p2.hp - self.ad - p1.ad print('%s利用%s攻击了%s,%s还剩%s血' % (p1.name, pillow.name, p2.name, p2.name, p2.hp)) gailun = GameRole('盖伦', 10, 100) yasuo = GameRole('剑豪', 20, 80) pillow = Weapon('绣花枕头', 2) # pillow.weapon_attack(gailun, yasuo) gailun.equip_weapon(pillow) gailun.wea.weapon_attack(gailun, yasuo)
依赖关系:给一个类的方法传了一个参数此参数是另一个类的对象(类名)。
# 这种依赖关系是所有关系中紧密型最低的,耦合性最低的。 # 冰箱依赖大象,就好比企业与兼职工的关系,你中有我,我中没有你。 class Elphant: def __init__(self, name): self.name = name def open(self, obj): print('芝麻开门') obj.open_door() def close(self, obj): print('芝麻关门') obj.close_door() class Refrigerator: def __init__(self, name): self.name = name def open_door(self): print('门开了') def close_door(self): print('门关了') e1 = Elphant('壮象') medai = Refrigerator('美的') e1.open(medai) # e1.close(medai)
关联关系:将一个对象的属性赋值 修改为另一个对象
class Boy: def __init__(self, name, grilfriend=None): self.name = name self.grilfriend = grilfriend def have_a_dinner(self): if self.grilfriend: print('%s和%s一起共度晚餐' % (self.name, self.grilfriend.name)) else: print('吃海鲜') def add_grilfriend(self, gril): self.grilfriend = gril # 将一个对象的属性赋值 修改为另一个对象 def remove_grilfriend(self): self.grilfriend = None class Gril: def __init__(self, name): self.name = name b = Boy('rock') # b.have_a_dinner() g = Gril('小七') b.add_grilfriend(g) # 将一个对象的属性赋值 修改为另一个对象 # b.have_a_dinner() b.remove_grilfriend() b.have_a_dinner()