定义一个Shap基类,并派生出圆球体和立方体类,在主函数中分别求圆球体与立方体对象的表面积和体积。
时间: 2023-06-19 09:06:16 浏览: 82
继承与派生声明一个哺乳动物类声明一个shap(形状)基类,
5星 · 资源好评率100%
好的,我明白了。以下是代码实现:
```python
import math
class Shape:
def surface_area(self):
pass
def volume(self):
pass
class Sphere(Shape):
def __init__(self, radius):
self.radius = radius
def surface_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, side_length):
self.side_length = side_length
def surface_area(self):
return 6 * (self.side_length ** 2)
def volume(self):
return self.side_length ** 3
# 主函数
def main():
sphere = Sphere(5)
print("Sphere surface area:", sphere.surface_area())
print("Sphere volume:", sphere.volume())
cube = Cube(10)
print("Cube surface area:", cube.surface_area())
print("Cube volume:", cube.volume())
if __name__ == '__main__':
main()
```
当你运行代码时,它会输出以下结果:
```
Sphere surface area: 314.1592653589793
Sphere volume: 523.5987755982989
Cube surface area: 600
Cube volume: 1000
```
阅读全文