给预置代码中的矩形和圆形类添加计算周长功能,并在__str__()
函数中体现出来。
注:计算周长方法名必须为getCircumference
。
程序输出如下所示
Rectanger--> Color: red Area:200.00 Circumference: 60.00
Circle--> Color: Green Area:1256.00 Circumference: 125.60
Rectanger--> Color: Yellow Area:72.00 Circumference: 36.00
Circle--> Color: Pink
#抽象图形类
class Shape:
def __init__(self,color):
self.color=color
def getArea(self):
return 0
def getCircumference(self):
return 0
def __str__(self):
return "Color: "+self.color
#矩形类
class Rect(Shape):
def __init__(self,color,length,width):
Shape.__init__(self,color)
self.length = length
self.width = width
def getArea(self):
return self.length*self.width
def getCircumference(self):
return 2*(self.length+self.width)
def __str__(self):
return f"Rectanger--> { super().__str__()} Area:{ self. getArea():.2f} Circumference:{self.getCircumference():.2f}"
#圆类
class Circle(Shape):
def __init__(self,color,radius):
Shape.__init__(self,color)
self.radius=radius
def getArea(self):
return 3.14*self.radius**2
def getCircumference(self):
return 2*3.14*self.radius
def __str__(self):
return f"Circle-->{ super().__str__()} Area:{ self. getArea():.2f} Circumference:{self.getCircumference():.2f}"
shapes = []
shapes.append(Rect('red',10,20))
shapes.append(Circle('Green',20))
shapes.append(Rect('Yellow',12,6))
shapes.append(Circle('Pink',10))
for shape in shapes:
print(shape)