1. 程式人生 > >面向物件-小練習

面向物件-小練習

練習:編寫一個學生類,產生一堆學生物件
要求:有一個計數器(屬性),統計總共實力化多少個物件
class Student:
    school = 'luffycity'
    count = 0

    def __init__(self, name, sex, age):  # 獨有特徵
        self.Name = name
        self.Sex = sex
        self.Age = age
        Student.count += 1  # 核心,這樣是累加呼叫的次數;self.count 是物件自己一個 值為1

    def learn(self):  #
技能 print('is learning') stu1 = Student("alex",'male',28) stu2 = Student("egon",'male',18) stu3 = Student("wusi",'male',27) print(stu1.count) print(stu2.count) print(stu3.count)
練習2:模仿LOL定義兩個英雄類,
要求:

英雄有暱稱,攻擊力,生命值等屬性;
例項化兩個英雄物件
英雄之間可以互毆,被毆掉一方的掉血,血量小於0則判斷死亡。
class Garen:
    camp = 'camp
' def __init__(self,nickname,life_value,aggresivity): self.nickname=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value -= self.aggresivity class Riven: camp = 'Noxus' def __init__(self,nickname,life_value,aggresivity): self.nickname
=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value -= self.aggresivity # if enemy.life_value <= 0: g1=Garen('草叢倫',100,30) r1=Riven('芮雯雯',80, 50) print(r1.life_value) g1.attack(r1) g1.attack(r1) g1.attack(r1) print(g1.attack(r1)) print(r1.life_value)