4.12

时长:三个小时

8-2 【Python0015】以圆类为基础设计三维图形体系
分数 10
作者 doublebest
单位 石家庄铁道大学

【题目描述】设计三维图形类体系,要求如下:

设计三维图形功能接口,接口包含周长、面积、体积计算方法;

基于以上接口,首先定义点类,应包含x,y坐标数据成员,坐标获取及设置方法、显示方法等;

以点类为基类派生圆类,增加表示半径的数据成员,半径获取及设置方法,重载显示函数,并可计算周长和面积等;

以圆类为基础派生球类、圆柱类、圆锥类;要求派生类球、圆柱、圆锥中都含有输入和输出显示方法;并可计算面积、周长。

程序中定义各种类的对象,并完成测试。
【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。

问题:

代码量:

from abc import ABC, abstractmethod

class ThreeDShapeInterface(ABC):
@abstractmethod
def perimeter(self):
pass

@abstractmethod
def area(self):
pass

@abstractmethod
def volume(self):
pass

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def get_coordinates(self):
return self.x, self.y

def set_coordinates(self, x, y):
self.x = x
self.y = y

def display(self):
print(f"坐标: ({self.x}, {self.y})")

import math

def base_area(radius):
"""
计算圆的面积

参数:
radius: 圆的半径

返回:
圆的面积
"""
area = math.pi * (radius ** 2)
return area


class Circle(Point, ThreeDShapeInterface):
def __init__(self, x=0, y=0, radius=1):
super().__init__(x, y)
self.radius = radius

def get_radius(self):
return self.radius

def set_radius(self, radius):
self.radius = radius

def display(self):
super().display()
print(f"半径: {self.radius}")

def perimeter(self):
return 2 * math.pi * self.radius

def area(self):
return math.pi * self.radius ** 2

# 圆作为二维图形,没有体积
def volume(self):
raise NotImplementedError("ERROR")

class Sphere(Circle):
def __init__(self, x=0, y=0, radius=1):
super().__init__(x, y, radius)

def volume(self):
return 4/3 * math.pi * self.radius ** 3

class Cylinder(Circle):
def __init__(self, x=0, y=0, radius=1, height=1):
super().__init__(x, y, radius)
self.height = height

def get_height(self):
return self.height

def set_height(self, height):
self.height = height

def display(self):
super().display()
print(f"高: {self.height}")

def area(self):
base_area = super().area()
side_area = 2 * math.pi * self.radius * self.height
return 2 * base_area + side_area

def volume(self):
return base_area * self.height

class Cone(Circle):
def __init__(self, x=0, y=0, radius=1, height=1):
super().__init__(x, y, radius)
self.height = height

def get_height(self):
return self.height

def set_height(self, height):
self.height = height

def display(self):
super().display()
print(f"高: {self.height}")

def area(self):
base_area = super().area()
slant_height = math.sqrt(self.radius**2 + self.height**2)
side_area = math.pi * self.radius * slant_height
return base_area + side_area

def volume(self):
return 1/3 * base_area * self.height

point = Point(3, 4)
point.display()

circle = Circle(0, 0, 5)
circle.display()
print(f"周长: {circle.perimeter()}, 面积: {circle.area()}")

sphere = Sphere(1, 2, 3)
sphere.display()
print(f"体积: {sphere.volume()}")

cylinder = Cylinder(0, 0, 4, 6)
cylinder.display()
print(f"面积: {cylinder.area()}, 体积: {cylinder.volume()}")

cone = Cone(0, 0, 4, 6)
cone.display()
print(f"面积: {cone.area()}, 体积: {cone.volume()}")
posted @ 2024-06-19 17:53  孙锺鸣  阅读(2)  评论(0编辑  收藏  举报