定义一个Shape基类,并派生出圆球体(Shape)和立方体类(Cube),分别求圆球体与立方体对象的表面积和体积
时间: 2024-03-02 17:48:01 浏览: 56
可以参考如下代码实现:
```python
import math
class Shape:
def area(self):
pass
def volume(self):
pass
class Sphere(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 4 * math.pi * self.radius ** 2
def volume(self):
return 4 / 3 * math.pi * self.radius ** 3
class Cube(Shape):
def __init__(self, edge_length):
self.edge_length = edge_length
def area(self):
return 6 * self.edge_length ** 2
def volume(self):
return self.edge_length ** 3
# 示例用法
sphere = Sphere(3)
cube = Cube(4)
print("Sphere area:", sphere.area())
print("Sphere volume:", sphere.volume())
print("Cube area:", cube.area())
print("Cube volume:", cube.volume())
```
输出结果为:
```
Sphere area: 113.09733552923254
Sphere volume: 113.09733552923254
Cube area: 96
Cube volume: 64
```
阅读全文