面向对象之组合

1、对象和类空间

在学习组合前,先了解一下对象和类空间。

# 对象与对象之间是不能互相访问,彼此独立。
# 对象可以访问类中的所有内容,但是类名不能访问对象中的内容。

# 组合的作用:让类的对象与另一个类的对象发生关联,从而可以互相访问。下面具体说明

完成王者荣耀,游戏人物相互打斗的功能。
class Game_Role:
    area = '召唤师峡谷'
    def __init__(self, name, sex, ad, hp):
        
        self.name = name
        self.sex = sex
        self.ad = ad
        self.hp = hp
    def fight(self, role1):
        role1.hp = role1.hp - self.ad
        print('%s 攻击 %s, %s还剩余%s' % (self.name, role1.name, role1.name, role1.hp))
        # print(self, role1)
    def equit_weapon(self, wea):
        self.wea = wea  # 组合: 对象中的属性是另一个类的对象
        
        
class Weapon:
    
    def __init__(self,name,ad):
        self.name = name
        self.ad = ad
    
    def wea_attack(self, role1, role2):
        role2.hp = role2.hp - self.ad
        print('%s 利用 %s 攻击 %s, %s还剩余%s' % (role1.name,self.name, role2.name, role2.name, role2.hp))

p1 = Game_Role('盖伦', 'man', 30, 500)
p2 = Game_Role('狗头', '', 50, 250)
# p3 = Game_Role('诺克', 'man', 50, 350)
# p1.fight(p2)

sword = Weapon('大宝剑', 40)
# print(sword)
# sword.wea_attack(p1, p2)
p1.equit_weapon(sword)  # 此方法就是给p1对象封装一个属性,属性值是sword对象
# print(p1.wea.name)
# # print(p1.wea)
p1.wea.wea_attack(p1,p2)  # 通过p1.wea找到sword 然后在sword.wea_attack执行方法

 组合其他示例:

class A:
    n1 = '太白'

    def __init__(self, name1, age1):
        self.name = name1
        self.age = age1


    def func(self):
        print(self.name)
        self.func1()
        print(self.n1)
        print(666)

    def func1(self):
        print(777)

obj = A('alex', 73)
obj.func()

class B:
    n2 = 'WuSir'

    def func3(self):
        print('in func3')

b1 = B()

obj.b = b1  # 组合
print(obj.b.n2)

 

原文地址:https://www.cnblogs.com/wangkaiok/p/9950161.html