类、对象空间,组合
job1 = 'teacher' class A: home = '老男孩教育' name = '武大' def __init__(self, name, age): self.name = name self.age = age def job(self): print('我在开车.....') 查询顺序 对象的查询顺序:先从对象空间去找,对象的空间没有此变量或者方法,通过对象中的类对象指针去类中寻找. obj1 = A('oldboy',1000) obj1 = A('oldboy',1000) obj1 = A('oldboy',1000) obj1 = A('oldboy',1000) print(obj1.name) print(obj1.job) print(obj1.home) 类的查询顺序: 直接从类本身找. print(A.name)
# 对象的问题
# 无论创建多少对象,都是开辟独立的空间,各个对象之间不能互相查找,干扰.
# obj1 = A('oldboy',1000)
# obj2 = A('alex',10000)
# 计算一个类实例化多少个对象 # class A: # home = '老男孩教育' # name = '武大' # count = 0 # def __init__(self, name, age): # A.count = A.count + 1 # self.name = name # self.age = age # def job(self): # print('我在开车.....') # # obj1 = A('alex1',1000) # obj2 = A('alex2',1000) # obj3 = A('alex3',1000) # obj4 = A('alex4',1000) # print(A.count)
# 组合: 给一个类的对象,封装一个属性,这个属性是另一个类的对象. class Game_role: def __init__(self, name, ad, hp): self.name = name self.ad = ad self.hp = hp def attack(self,obj1): obj1.hp = obj1.hp - self.ad print('%s攻击%s,%s掉了%s血,还剩%s血'%(self.name,obj1.name,obj1.name,self.ad,obj1.hp)) def package_weapon(self,wea): self.weapon = wea class Sword: 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血' %(p1.name,self.name,p2.name,p2.name,p2.hp)) # aduan = Game_role('啊段', 10, 100) # ts = Game_role('泰森', 120, 300) # Slaughter_knife = Sword('杀猪刀',200) # 这么写不好,动作的发起人是人而不是刀本身 # Slaughter_knife.fight(aduan,ts) # 下面是符合逻辑的 # aduan.package_weapon(Slaughter_knife) # 给aduan 这个对象封装了一个weapon属性这个属性值为Slaughter_knife # aduan.weapon.fight(aduan,ts) # ts.attack(aduan) # print(aduan.weapon) # print(aduan.weapon.name) # aduan.weapon.fight(aduan,ts)