练习22——初识面向对象
1.人狗大战
class Person: def __init__(self, name, blood, aggr, sex): self.name = name self.blood = blood self.aggr = aggr self.sex = sex def attack(self, dog): dog.blood -= self.aggr class Dog: def __init__(self, name, blood, aggr, kind): self.name = name self.blood = blood self.aggr = aggr self.kind = kind def bite(self, person): person.blood -= self.aggr jin = Dog('金老板', 100, 20, 'teddy') alex = Person('alex', 200, 10, '未知') alex.attack(jin) jin.bite(alex) print(jin.blood) print(alex.blood)
2.圆周长面积、正方形周长面积
circle 属性 半径 ,两个方法:求周长和面积 from math import pi class circle: def __init__(self, r): self.r = r def area(self): print('面积是:{:.2f}'.format(pi * self.r**2)) def perimeter(self): print('周长是:{:.2f}'.format(pi * self.r * 2)) c = circle(5) c.area() c.perimeter() #正方形的面积和周长 class cube: def __init__(self, l): self.l = l def area(self): print('面积:{}'.format(self.l**2)) def perimeter(self): print('周长:{}'.format(self.l*4)) cu1 = cube(5) cu1.area() cu1.perimeter()