知行合一
Choose a quality life!
2,定义一个类,计算圆的周长和面积。
from math import pi
class Circle:
def __init__(self,r):
self.r = r
def area(self):
return round(self.r ** 2 * pi,2)
def perimeter(self):
return round(self.r * 2 * pi,2)
# c1 = Circle(5)
# print(c1.area())
# print(c1.perimeter())
# 3,定义一个圆环类,计算圆环的周长和面积(升级题)。
class Ring:
def __init__(self,r1,r2):
self.r1 = r1
self.r2 = r2
def area(self):
return round(self.r1 ** 2 * pi - self.r2 ** 2 * pi, 2)
def perimeter(self):
return round(self.r1 * 2 * pi + self.r2 * 2 * pi, 2)
r1 = Ring(6,3)
print(r1.area())
print(r1.perimeter())
组合的思想
class Ring:
def __init__(self,r1,r2):
self.r1 = Circle(r1)
self.r2 = Circle(r2)
def area(self):
return self.r1.area() - self.r2.area()
def perimeter(self):
return self.r1.perimeter() + self.r2.perimeter()
r = Ring(6,3)
print(r1.area())
print(r1.perimeter())
posted on 2018-07-25 20:09  小米没吃饭  阅读(273)  评论(0编辑  收藏  举报