定义一个形状类(Shape)方法:计算周长,计算面积 子类: 矩形类(Rectangle) :额外的方法:differ() 计算长宽差 圆形类(Circle) 三角形类(Triangle) 正方形类(Square) 矩形的子类 生成几个不同的形状对象,放在一个 Shape 类型的数组里,分别求每个形状的周长和面积。 如果形状对象是一个矩形,且不是正方形,则计算长宽差。
时间: 2024-01-07 22:05:17 浏览: 230
好的,以下是我给出的代码示例:
```python
class Shape:
def __init__(self):
pass
def calculate_perimeter(self):
pass
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
def calculate_area(self):
return self.length * self.width
def differ(self):
return abs(self.length - self.width)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_perimeter(self):
return 2 * 3.14 * self.radius
def calculate_area(self):
return 3.14 * self.radius ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def calculate_perimeter(self):
return 3 * self.base
def calculate_area(self):
return 0.5 * self.base * self.height
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
shapes = [Rectangle(4, 5), Circle(3), Triangle(6, 8), Square(5)]
for shape in shapes:
print("Perimeter:", shape.calculate_perimeter())
print("Area:", shape.calculate_area())
if isinstance(shape, Rectangle) and shape.length != shape.width:
print("Difference:", shape.differ())
print()
```
这个代码会输出每个形状的周长和面积,如果是矩形且不是正方形,还会输出长宽差。你可以根据需要进行修改和扩展。
阅读全文