1. 写一个求正方形周长和面积的类
1 class Square: 2 def __init__(self, length): 3 self.length = length 4 def area(self): 5 return '边长为{}的正方形的面积为:{}'.format(self.length, self.length**2) 6 def perimeter(self): 7 return '边长为{}的正方形的周长为:{}'.format(self.length, self.length * 4) 8 z1 = Square(5) 9 print(z1.area()) 10 print(z1.perimeter())
2. 完成人狗大战
1 class Dogs: 2 def __init__(self,name,HP,aggr,kind): 3 self.name = name 4 self.HP = HP 5 self.aggr = aggr 6 self.kind = kind 7 8 # 狗:攻击技能(咬人) 9 def bite(self,person): 10 # 狗咬人,人掉血 11 person.HP -= self.aggr 12 if person.HP <= 0: 13 print('%s被%s咬死了, 扑街...') % (person.name, self.name) 14 else: 15 print('%s被%s咬了, 掉了%s滴血, 还剩%s滴血' % (person.name, self.name ,self.aggr,person.HP)) 16 17 class Person: 18 def __init__(self,name,HP,aggr,sex): 19 self.name = name 20 self.HP = HP 21 self.aggr = aggr 22 self.sex = sex 23 24 # 人:攻击技能(打) 25 def attack(self,dog): 26 dog.HP -= self.aggr 27 if dog.HP <= 0: 28 print('%s被%s打死了, 扑街...' % (dog.name, self.name)) 29 else: 30 print('%s被%s打了, 掉了%s滴血, 还剩%s滴血' % (dog.name, self.name ,self.aggr,dog.HP)) 31 32 33 jin = Dogs('二狗', 300, 1, '泰迪') 34 alex = Person('人', 200, 500, '不详') 35 jin.bite(alex) # Dogs.bite(jin,alex) 36 alex.attack(jin)
3. 默写 面向对象的交互里面的内容