练习1:编写一个学生类,产生一堆学生对象
要求:
有一个计数器(属性),统计总共实例了多少个对象
class Student: school = "Luffycity" #类的数据属性 类变量 count = 0 def __init__(self,age,name): #独有的特征 self.age = age self.name = name Student.count += 1 def learn(self): #类的函数属性 print('%s is learning'%self.name) zhan = Student(18,'zhan') yang = Student(18,'yang') print(Student.count) print(zhan.count) print(yang.count)
练习2:模仿王者荣耀定义两个英雄类
要求:
英雄需要有昵称、攻击力、生命值等属性;
实例化出两个英雄对象;
英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡。
class Hero:
def __init__(self,name,damage,zing):
self.name = name
self.damage = damage
self.zing = zing
def attack(self,enemy):
while True:
enemy.zing -= self.damage
self.zing -= enemy.damage
if self.zing == 0:
print("%s 已经死亡"%self.name)
break
elif enemy.zing == 0:
print("%s 已经死亡"%enemy.name)
break
class Yang(Hero):
pass
class Lin(Hero):
pass
g1 = Yang('Yang',100,500)
r1 = Lin('Lin',100,200)
g1.attack(r1)