python中類和類的組合,依賴,關聯關係

python中類和類的組合,依賴,關聯關係

轉載自:(https://www.cnblogs.com/chen55555/articles/10279008.html)

組合關係:將一個對象封裝到另一個對象的屬性中

  • 組合的好處:
    • 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()

轉載自:https://www.cnblogs.com/chen55555/articles/10279008.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章