
# 3处可以添加对象属性# 在__init__内# 在类的内部(方法中)# 在类的外部class Human: mind = '有思想的' def __init__(self,name): self.name = name # 在init方法中 def eat(self,argv): self.argv = argvsun = 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 = argvsun = 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 = zhouliye.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('长缨q',30)gailun.equipment_wea(Sword)# 给游戏人物封装武器属性gailun.weapon.weapon_attack(gailun,xin) 总结 以上是内存溢出为你收集整理的Python 第二十二章全部内容,希望文章能够帮你解决Python 第二十二章所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)