python (面向对象:组合)

一. 组合

  给一个类的对象封装另一个类的对象.

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))
p1 = GameRole('大阳哥',20,500)
p2 = GameRole('印度阿宁',50,200)
axe = Weapon('三板斧',60)
broadsword = Weapon('屠龙宝刀',100)
p1.armament_weapon(axe)  # 给大阳哥 装备了三板斧这个对象.
p1.wea.fight(p1,p2)    #使用带有了其他类中对象的本类对象去调用对应其他类中的方法

#结果:
#大阳哥 用三板斧打了印度阿宁,印度阿宁 掉了60血,还剩140血
  查询顺序:
    对象.属性:先从对象空间找,如果找不到,再从类空间找,如果还找不到,再从父类找
    类名.属性:先从本类空间找,如果找不到,再从父类空间找
  对象和对象之间是互相独立的

二. 计算一个类实例化多少对象

class Count:
    count = 0
    def __init__(self):
        Count.count = Count.count + 1
obj1 = Count()
obj2 = Count()
print(Count.count)

 

  

posted @ 2018-07-25 10:58  唯你如我心  阅读(157)  评论(0编辑  收藏  举报