试写出你所能想到的所有形状(包括二维的和三维的),生成一个形状层次类体系。生成的类体系以Shape作为基类,并由此派生出TwoDimShape类和 ThreeDimShape类。它们的派生类是不同的形状类。定义类体系中的每个类,并用main函数进行测试。
时间: 2023-06-11 18:09:48 浏览: 118
以下是我编写的代码:
```python
class Shape:
def __init__(self):
pass
def get_area(self):
pass
def get_volume(self):
pass
class TwoDimShape(Shape):
def __init__(self):
super().__init__()
def get_area(self):
pass
class ThreeDimShape(Shape):
def __init__(self):
super().__init__()
def get_area(self):
pass
def get_volume(self):
pass
class Circle(TwoDimShape):
def __init__(self, radius):
super().__init__()
self.radius = radius
def get_area(self):
return 3.14 * self.radius * self.radius
class Square(TwoDimShape):
def __init__(self, side):
super().__init__()
self.side = side
def get_area(self):
return self.side ** 2
class Triangle(TwoDimShape):
def __init__(self, base, height):
super().__init__()
self.base = base
self.height = height
def get_area(self):
return 0.5 * self.base * self.height
class Sphere(ThreeDimShape):
def __init__(self, radius):
super().__init__()
self.radius = radius
def get_area(self):
return 4 * 3.14 * self.radius * self.radius
def get_volume(self):
return 4 / 3 * 3.14 * self.radius ** 3
class Cube(ThreeDimShape):
def __init__(self, side):
super().__init__()
self.side = side
def get_area(self):
return 6 * self.side ** 2
def get_volume(self):
return self.side ** 3
class Cylinder(ThreeDimShape):
def __init__(self, radius, height):
super().__init__()
self.radius = radius
self.height = height
def get_area(self):
return 2 * 3.14 * self.radius * self.height + 2 * 3.14 * self.radius ** 2
def get_volume(self):
return 3.14 * self.radius ** 2 * self.height
if __name__ == "__main__":
circle = Circle(5)
print(f"Circle area: {circle.get_area()}")
square = Square(7)
print(f"Square area: {square.get_area()}")
triangle = Triangle(3, 4)
print(f"Triangle area: {triangle.get_area()}")
sphere = Sphere(5)
print(f"Sphere area: {sphere.get_area()}, volume: {sphere.get_volume()}")
cube = Cube(7)
print(f"Cube area: {cube.get_area()}, volume: {cube.get_volume()}")
cylinder = Cylinder(3, 5)
print(f"Cylinder area: {cylinder.get_area()}, volume: {cylinder.get_volume()}")
```
在这个类层次结构中,Shape是基类,TwoDimShape和ThreeDimShape是直接从Shape派生出来的子类。然后,我们派生了不同的形状类(例如,Circle、Square、Triangle、Sphere、Cube和Cylinder),它们分别继承了TwoDimShape和ThreeDimShape类,并实现了它们各自的get_area()和get_volume()方法。在main函数中,我们创建了这些形状的对象,并测试它们各自的方法。
阅读全文