5.24

所学时间:2小时

代码行数:200

博客园数:1篇

所学知识:

(二)、以圆类为基础设计三维图形体系

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

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

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

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

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

程序中定义各种类的对象,并完成测试。

【源代码程序】

import math

 

# 三维图形功能接口

class Shape3D:

    def get_area(self):

        pass

 

    def get_volume(self):

        pass

 

# 点类

class Point:

    def __init__(self, x, y):

        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"Point coordinates: ({self.x}, {self.y})")

 

# 圆类

class Circle(Point, Shape3D):

    def __init__(self, x, y, radius):

        super().__init__(x, y)

        self.radius = radius

 

    def get_area(self):

        return math.pi * self.radius ** 2

 

    def display(self):

        super().display()

        print(f"Radius: {self.radius}")

 

# 球类

class Sphere(Circle):

    def get_volume(self):

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

 

# 圆柱类

class Cylinder(Circle, Shape3D):

    def __init__(self, x, y, radius, height):

        super().__init__(x, y, radius)

        self.height = height

 

    def get_area(self):

        return 2 * math.pi * self.radius * (self.radius + self.height)

 

    def get_volume(self):

        return math.pi * self.radius ** 2 * self.height

 

# 圆锥类

class Cone(Circle, Shape3D):

    def __init__(self, x, y, radius, height):

        super().__init__(x, y, radius)

        self.height = height

 

    def get_area(self):

        base_area = super().get_area()

        side_area = math.pi * self.radius * math.sqrt(self.radius ** 2 + self.height ** 2)

        return base_area + side_area

 

    def get_volume(self):

        return (1/3) * math.pi * self.radius ** 2 * self.height

 

# 测试类的创建和计算

circle1 = Circle(0, 0, 5)

sphere1 = Sphere(0, 0, 5)

cylinder1 = Cylinder(0, 0, 5, 10)

cone1 = Cone(0, 0, 5, 10)

 

print("Circle Information:")

circle1.display()

print(f"Area: {circle1.get_area()}\n")

 

print("Sphere Information:")

sphere1.display()

print(f"Volume: {sphere1.get_volume()}\n")

 

print("Cylinder Information:")

cylinder1.display()

print(f"Area: {cylinder1.get_area()}")

print(f"Volume: {cylinder1.get_volume()}\n")

 

print("Cone Information:")

cone1.display()

print(f"Area: {cone1.get_area()}")

print(f"Volume: {cone1.get_volume()}")

posted @ 2024-05-24 17:28  Snor9  阅读(16)  评论(0)    收藏  举报