面向物件 4 面向物件可擴充套件性總結&練習
阿新 • • 發佈:2018-12-12
class Chinese: country='China' def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def eat(self): print('%s is eating'%self.name) p1=Chinese('egon',16,'male') p2=Chinese('alex',11,'male') p3=Chinese('cindy',22,'female') p1.eat() p2.eat() p3.eat()
#練習1 編寫一個學生類,產生一堆學生物件 #要求 #有一個計算器屬性,統計共例項了多少物件 # # class Student: # school='luffycity' # count=0 # # def __init__(self,name,age,sex): # self.name=name # self.age=age # self.sex=sex # # self.count=self.count+1 # Student.count+=1 # # def learn(self): # print('%s is learning'%self.name) # # stu1=Student('alex',10,'male') # stu2=Student('jerry',22,'male') # stu3=Student('egon',33,'male') # # print(Student.count) # print(stu1.count) ''' 練習2 模仿lol定義兩個英雄類 要求 英雄需要有暱稱、攻擊力、生命值等屬性 例項化出兩個英雄物件 英雄之間可以互毆,被毆打的一方掉血,血量小於0則判定為死亡 ''' class Garen: camp='Demacia' 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 g1=Garen('草叢倫',100,30) r1=Riven('瑞文',80,50) g1.attack(r1) print(g1.life_value) print(r1.life_value)