写一个小练习,定义好一个类,每初始化一次,计数器+1,统计最后次数.
class OldboyStudent: school = ‘oldboy‘ count=0 def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex OldboyStudent.count+=1 def learn(self): print(‘%s is learning‘ %self.name) def eat(self): print(‘is eating‘) obj1=OldboyStudent(‘李大炮‘,18,‘女‘) obj2=OldboyStudent(‘张全蛋‘,28,‘男‘) obj3=OldboyStudent(‘牛榴弹‘,18,‘女‘) print(OldboyStudent.count)
写一个小程序,能够实现类之间的类的交互:
eg:例如LOL的英雄,互相攻击,交互剩余血量的问题
1 class Garen: 2 camp=‘Demacia‘ 3 def __init__(self,nickname,life_value=100,aggresivity=80): 4 self.nickname=nickname 5 self.life_value=life_value 6 self.aggresivity=aggresivity 7 def attack(self,enemy): 8 enemy.life_value-=self.aggresivity #敌人的血等于敌人的生命值减去我的攻击力 9 10 class Riven: 11 camp = ‘Noxus‘ 12 def __init__(self, nickname, life_value=80, aggresivity=100): 13 self.nickname = nickname 14 self.life_value = life_value 15 self.aggresivity = aggresivity 16 17 def attack(self, enemy): 18 enemy.life_value -= self.aggresivity 19 20 21 g1=Garen(‘草丛猥琐男‘) 22 r1=Riven(‘兔女郎‘) 23 24 print(r1.life_value) 25 g1.attack(r1) 26 print(r1.life_value)
时间: 2024-10-12 22:45:23