欢迎访问宙启技术站
智能推送

使用Python编写的BoxAdapter类

发布时间:2023-12-11 15:03:08

BoxAdapter类是一个用Python编写的适配器类,用于将不同类型的箱子适配成统一的接口,以便在其他代码中使用。该类包含以下方法和属性:

1. __init__(self, box):构造函数,用于初始化一个BoxAdapter对象。参数box表示要适配的箱子对象。

2. get_volume(self):获取适配的箱子的体积。返回值为一个浮点数,表示箱子的体积。

下面是一个使用BoxAdapter类的例子:

class CuboidBox:
    def __init__(self, width, height, depth):
        self.width = width
        self.height = height
        self.depth = depth

    def get_volume(self):
        return self.width * self.height * self.depth

class CylinderBox:
    def __init__(self, radius, height):
        self.radius = radius
        self.height = height

    def get_volume(self):
        return 3.14159 * self.radius * self.radius * self.height

class BoxAdapter:
    def __init__(self, box):
        self.box = box

    def get_volume(self):
        return self.box.get_volume()

# 创建一个CuboidBox对象
cuboid_box = CuboidBox(10, 20, 30)
# 创建一个CylinderBox对象
cylinder_box = CylinderBox(5, 10)

# 创建两个BoxAdapter对象,分别适配CuboidBox和CylinderBox
cuboid_box_adapter = BoxAdapter(cuboid_box)
cylinder_box_adapter = BoxAdapter(cylinder_box)

# 调用适配器的get_volume方法获取体积
print("CuboidBox的体积为:", cuboid_box_adapter.get_volume())
print("CylinderBox的体积为:", cylinder_box_adapter.get_volume())

输出结果为:

CuboidBox的体积为: 6000
CylinderBox的体积为: 785.39815

在上面的例子中,首先定义了一个CuboidBox类和一个CylinderBox类,它们分别表示长方体和圆柱体的箱子。这两个类都有一个get_volume方法,用于计算箱子的体积。

然后定义了一个BoxAdapter类,该类的构造函数接受一个箱子对象作为参数,并将其保存在self.box属性中。适配器类的get_volume方法直接调用了适配的箱子对象的get_volume方法,从而将不同类型的箱子适配成统一的接口。

在主程序中,首先创建了一个CuboidBox对象和一个CylinderBox对象。然后分别创建了两个适配器对象,分别适配了CuboidBoxCylinderBox。最后调用适配器的get_volume方法来获取适配的箱子的体积。