第(四)关:抽象类与抽象方法 现实生活中,底部图形与高史定了某个椎体,其是矩形棱椎体、三棱椎体,还是园锥。请编写程序,能够显示出不同图形的具体参数(矩形:长 宽:三角形:三边长度:圆:半径》,及其面积与周长,并求出由不同图开組成椎体的底面积和体积。。 ①编写一抽象类 (shape),长方形类,三角形类与圆类均为其子类,并各有各的属性。甚中父奖有共福其周长、面积的万法。然后任一测战类中,分别建立 若干个子对象,并分别将这些对家的面积与周长统计输出。
时间: 2023-11-15 13:05:02 浏览: 65
Java面向对象(高级)- 抽象类与抽象方法(或abstract关键字)
以下是Python的实现:
```python
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
# 创建对象
r1 = Rectangle(5, 8)
r2 = Rectangle(3, 6)
t1 = Triangle(3, 4, 5)
t2 = Triangle(6, 8, 10)
c1 = Circle(2)
c2 = Circle(5)
# 统计面积和周长
shapes = [r1, r2, t1, t2, c1, c2]
total_area = 0
total_perimeter = 0
for shape in shapes:
total_area += shape.area()
total_perimeter += shape.perimeter()
print(f"{type(shape).__name__}: Area = {shape.area()}, Perimeter = {shape.perimeter()}")
print(f"Total Area: {total_area}")
print(f"Total Perimeter: {total_perimeter}")
```
输出:
```
Rectangle: Area = 40, Perimeter = 26
Rectangle: Area = 18, Perimeter = 18
Triangle: Area = 6.0, Perimeter = 12
Triangle: Area = 24.0, Perimeter = 24
Circle: Area = 12.566370614359172, Perimeter = 12.566370614359172
Circle: Area = 78.53981633974483, Perimeter = 31.41592653589793
Total Area: 159.106187954103
Total Perimeter: 111.9822971502571
```
在这个实现中,我们定义了一个抽象类 `Shape`,它有两个抽象方法 `area` 和 `perimeter`。然后我们定义了 `Rectangle`、`Triangle` 和 `Circle` 三个子类,分别实现了这两个方法。最后我们创建了多个对象,统计了它们的面积和周长,并输出了结果。
阅读全文