通过类数据属性统计实例化次数
class Student: school='luffcity' count=0 def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex Student.count+=1 def learn(self): print("% is learing" % self.name)stu1=Student('Alex','male',38)print(stu1.count)stu2=Student('Agon','male',88)print(stu2.count)
对象之间的交互
# 模仿LOL定义两个英雄class Garen: camp='Demacia' def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggersivity=aggresivity def attack(selfs,enemy): enemy.life_value -= selfs.aggersivityclass Riven: camp='Noxus' def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggersivity=aggresivity def attack(selfs,enemy): enemy.life_value -= selfs.aggersivityg1=Garen('草丛伦',100,30)g2=Riven('锐雯雯',80,50)g1.attack(g2)print(g1.life_value)print(g2.life_value)