第五章---面向对象---小练习

练习1:编写一个学生类,产生一堆学生对象
要求:
有一个计数器(属性),统计总共实例化了多少个对象
 1 class Student:
 2     school = 'luffycity'
 3     count = 0
 4 
 5     def __init__(self,name,age,sex):
 6         self.name = name
 7         self.age = age
 8         self.sex = sex
 9         # self.count += 1  # 只能累加到独有的对象上面
10         Student.count += 1 # 累加到全局的count上面
11 
12     def learn(self):
13         print('%s is learning'% self.name)
14 
15 stu1 = Student('mm',18,'')
16 stu2 = Student('mumu',1,'')
17 
18 print(stu1.count)
19 print(Student.count)
练习2:模仿LoL定义两个英雄类
要求:
英雄需要有昵称,攻击力,生命值等属性
实例化出两个英雄对象
英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡
 1 class HeroDog:
 2     def __init__(self,name,attack,life_value):
 3         self.name = name
 4         self.attack = attack
 5         self.life_value = life_value
 6 
 7     def attack_other(self,enemy):
 8         enemy.life_value -= self.attack
 9         if enemy.life_value <= 0:
10             print('%s 没有血量,宣布死亡!'% enemy.name)
11         else:
12             print('%s血量剩余%s'% (enemy.name,enemy.life_value))
13 
14 class HeroPig:
15     def __init__(self,name,attack,life_value):
16         self.name = name
17         self.attack = attack
18         self.life_value = life_value
19 
20     def attack_other(self,enemy):
21         enemy.life_value -= self.attack
22         if enemy.life_value <= 0:
23             print('%s 没有血量,宣布死亡!'% enemy.name)
24         else:
25             print('%s血量剩余%s'% (enemy.name,enemy.life_value))
26 
27 hero_d = HeroDog('dog',10,100)
28 hero_p = HeroPig('pig',20,80)
29 
30 hero_d.attack_other(hero_p)
31 hero_d.attack_other(hero_p)
32 hero_p.attack_other(hero_d)
33 hero_p.attack_other(hero_d)

猜你喜欢

转载自www.cnblogs.com/mumupa0824/p/8950324.html