标签:span ack 内容 动物 lex ict 而不是 try 一个
主要内容:
1. 类的名称空间查询顺序
查询空间:
对象的查询空间:先从对象空间找,如果找不到,再从类空间找,再找不到,从父类空间找.....
类的查询空间: 先从本类的空间找,如果找不到,再从父类空间找......
class Person:
animal = ‘高级动物‘
def __init__(self, country, name, sex):
self.country = country
self.name = name
self.sex = sex
def eat(self):
print(‘%s吃饭‘ % self.name)
def work(self):
print(‘工作‘)
Person.__dict__[‘work‘](11) #可以通过函数对应的地址+()调用改函数.
p1 = Person(‘china‘,‘alex‘,‘nan‘)
print(p1.__dict__)
print(p1.animal) #对象.属性 : 先从对象空间找,如果找不到,再从类空间找,再找不到,再从父类找....
print(Person.animal) #类名:属性: 先从本类空间找,如果找不到,再从父类找....
# 对象与对象之间是互相独立的.
p1.animal = ‘低级‘ #不能改变类中的变量,只能查询,试图改变,只能往对象里添加属性.
print(p1.__dict__) #{‘country‘: ‘china‘, ‘name‘: ‘alex‘, ‘sex‘: ‘nan‘, ‘age‘: ‘23‘, ‘hight‘: 175, ‘animal‘: ‘低级‘}
print(Person.__dict__) #{‘__module__‘: ‘__main__‘, ‘animal‘: ‘高级动物‘,
2. 计算一个类中,实例化多少次对象
class Count:
count = 0
def __init__(self):
Count.count = Count.count + 1
p1 = Count()
p1 = Count()
p1 = Count()
print(Count.count)
# 通过类名.变量,可以改变变量的值
Count.count = 6
print(Count.count)
# 通过对象,不能改变,只能引用
3. 组合
组合的定义:给一个类中的对象封装属性,该属性是另一个类中的对象
#滕攀用三板斧打了候,候掉了多少血,还剩多少血.
class Game_role:
def __init__(self,name,ad,hp):
self.name = name
self.ad = ad
self.hp = hp
def attack(self):
pass
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 = Game_role(‘滕攀‘,20,200)
p2 = Game_role(‘候‘,10,50)
aa = Weapon(‘三板斧‘,88)
tt = Weapon(‘宝刀‘,666)
# aa.fight(p1,p2) #代码不合理,人物是利用武器攻击别人呢,你的动作发起者是人,而不是武器.
# print(p2.hp)
p1.armament_weapon(aa) #给滕攀装了三板斧这个对象.
p1.wea.fight(p1,p2)
标签:span ack 内容 动物 lex ict 而不是 try 一个
原文地址:https://www.cnblogs.com/gyh412724/p/9360697.html