# 3处可以添加对象属性 # 在__init__内 # 在类的内部(方法中) # 在类的外部 class Human: mind = '有思想的' def __init__(self,name): self.name = name # 在init方法中 def eat(self,argv): self.argv = argv sun = Human('zhansan') sun.eat('饭') # 在内部 sun.age = 18 # 在外部 print(sun.__dict__) # 2处添加类的属性 # 类的内部 # 类的外部 class Human: mind = '有思想的' def __init__(self,name): self.name = name def eat(self,argv): self.argv = argv sun = Human('zhansan') sun.eat = '有脑' # 内部 Human.body = '有头' # 外部 print(Human.__dict__) # 对象空间与类空间有相同的名字,对象先从对象空间找 # 查询顺序: # 对象.名字 对象空间 类对象指针 类空间 父类空间 # 类名.名字 类空间 父类空间 sun.mind = '无脑' print(sun.mind) print(Human.mind)
# 1、依赖关系:主从之分 class Elphant: def __init__(self,name): self.name = name def open(self,obj1): print(f'{self.name}打开冰箱门') obj1.open_door() def close(self): print(f'{self.name}关闭冰箱门') haier.close_door() class Refrigerator: def __init__(self,name): self.name = name def open_door(self): print(f'{self.name}牌冰箱被打开') def close_door(self): print(f'{self.name}牌冰箱被关闭') # 依赖关系:将一个类的类名或者对象传入另一个类的方法中 qiqi = Elphant('大象') haier = Refrigerator('海尔') qiqi.open(haier) # 2、组合关系 class Boy: def __init__(self,name,girlfriend=None): self.name = name self.girlfriend = girlfriend def have_a_diner(self): if self.girlfriend: print(f'{self.name}请他的女朋友{self.girlfriend}一起烛光晚餐') else: print("吃什么") liye = Boy('liye') # 只封装了一个属性:girlfriend 为一个字符串的数据 liye.have_a_diner() liye.girlfriend = 'zhou' liye.have_a_diner() print(1) class Boy: def __init__(self,girlfriend=None): self.name = name self.girlfriend = girlfriend def have_a_diner(self): if self.girlfriend: print(f'{self.name}请他的女朋友{self.girlfriend.name}一起烛光晚餐') else: print("吃什么") def girl_skill(self): print(f'{self.name}的女朋友的技能') self.girlfriend.skill() class Girl: def __init__(self,age,boby): self.name = name self.age = age self.boby = boby def skill(self): print(f'{self.name}会做饭') liye = Boy("liyw") zhou = Girl("zhou",20,'好') liye.girlfriend = zhou liye.have_a_diner() liye.girl_skill() # 3、组合+依赖关系 class Gamerole: def __init__(self,ad,hp): self.name = name self.ad = ad self.hp = hp def attack(self,p1): p1.hp = p1.hp - self.ad print(f'{self.name}攻击{p1.name},谁掉了{self.ad}血,还剩{p1.ph}血') print(f'{p1.name}的血量{p1.hp}') def equipment_wea(self,wea): self.weapon = wea # 组合关系 给对象封装一个属性,该属性是另一类的对象 class Weapon: def __init__(self,ad): self.name = name self.ad = ad def weapon_attack(self,p1,p2): # 依赖关系 print(f'self--->:{self}') # self 永远默认接受本类实例化对象 p2.hp = p2.hp - self.ad print(f'{p1.name}利用{self.name}给了{p2.name}一下子,{p2.name}掉了{self.ad}血,还剩{p2.hp}血') gailun = Gamerole('太白',10,200) xin = Gamerole('金莲',100) Sword = Weapon('枕头',2) Musket = Weapon('长缨枪',30) gailun.equipment_wea(Sword) # 给游戏人物封装武器属性 gailun.weapon.weapon_attack(gailun,xin)