定义接口或类 Shape,定义求周长的方法length()。 定义如下类,实现接口Shape或父类Shape的方法。 (1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。 定义测试类ShapeTest,用Shape接口(或类)定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。 提示: 计算圆周长时PI取3.14。 输入格式: 输入多组数值型数据(double); 一行中若有1个数,表示圆的半径; 一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。 一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。(需要判断三个边长是否能构成三角形) 若输入数据中有0或负数,则不表示任何图形,周长为0。python
时间: 2024-03-20 15:44:18 浏览: 25
好的,下面是根据题意改进后的代码实现:
```python
import math
# Shape接口
class Shape:
def length(self):
pass
# 三角形类
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def length(self):
if self.a + self.b > self.c and self.a + self.c > self.b and self.b + self.c > self.a:
return self.a + self.b + self.c
else:
return 0
# 长方形类
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def length(self):
if self.length > 0 and self.width > 0:
return 2 * (self.length + self.width)
else:
return 0
# 圆形类
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def length(self):
if self.radius > 0:
return 2 * math.pi * self.radius
else:
return 0
# 测试类
if __name__ == '__main__':
while True:
line = input().strip()
if not line:
break
nums = list(map(float, line.split()))
if len(nums) == 1:
shape = Circle(nums[0])
elif len(nums) == 2:
shape = Rectangle(nums[0], nums[1])
elif len(nums) == 3:
shape = Triangle(nums[0], nums[1], nums[2])
else:
shape = None
if shape:
print("周长为:", shape.length())
else:
print("输入数据有误,无法构成图形!")
```
这个代码实现与之前的实现基本相同,只是在测试类ShapeTest中做了修改。循环读取输入的数据,根据数据的个数创建不同的类的对象,并调用它们的length()方法来输出周长。同时,对于无法构成图形的数据,输出提示信息。需要注意的是,由于输入数据可能有多组,所以需要使用while循环来不断读取数据,直到读取到空行为止。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)