Chapter 5 --- Object Oriented --- Small Exercises

Exercise 1: Write a student class that generates a bunch of student objects 
Requirement:
There is a counter (attribute) that counts how many objects are instantiated in total
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 # can only be accumulated to the unique object 
10          Student.count += 1 # accumulated to the global 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)

 

Exercise 2: Define two hero classes by imitating LoL 
Requirements:
Heroes need to have attributes such as nickname, attack power, health, etc.
Instantiate two hero objects
. Heroes can fight each other. The beaten party loses blood, and the blood volume is less than 0. judged to be dead
 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)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324877879&siteId=291194637