Python中如何通过关联在Figures类调用Rectangle类的方法
解决Figures类调用Rectangle方法的问题及代码优化
首先,核心需求是让Figures类通过关联关系调用Rectangle的方法,实现批量获取周长和面积。以下是修正并优化后的完整代码:
class Rectangle: def __init__(self, width=None, height=None): self.width = width self.height = height def __str__(self): return "Rectangle with width {width} cm and height {height} cm".format(width=self.width, height=self.height) def get_area(self): return self.width * self.height def get_perimeter(self): return (self.width + self.height) * 2 @staticmethod def get_info(): return "This class calculates perimeter and area of the rectangles" class Figures: def __init__(self): self.figures = [] def __str__(self): return f"Container containing {len(self.figures)} rectangle(s)" def __len__(self): return len(self.figures) def add_rectangle(self, width=None, height=None, rectangle=None): # 支持两种添加方式:直接传入宽高,或者传入已创建的Rectangle实例 if rectangle is not None and isinstance(rectangle, Rectangle): self.figures.append(rectangle) elif width is not None and height is not None: self.figures.append(Rectangle(width=width, height=height)) else: print("You didn't provide width/height properly or a valid Rectangle instance") def get_perimeters(self): # 遍历所有矩形实例,调用其get_perimeter方法,返回周长列表并输出 perimeters = [rect.get_perimeter() for rect in self.figures] print("Perimeters of all rectangles:", perimeters) return perimeters def get_areas(self): # 同理获取所有面积 areas = [rect.get_area() for rect in self.figures] print("Areas of all rectangles:", areas) return areas @staticmethod def get_info(): return "This class creates a container for instances of the Rectangle class" # 测试示例 if __name__ == "__main__": # 创建Figures容器 fig_container = Figures() # 添加矩形 fig_container.add_rectangle(width=15, height=13) fig_container.add_rectangle(width=12, height=25) # 也可以先创建Rectangle实例再添加 rect3 = Rectangle(width=10, height=20) fig_container.add_rectangle(rectangle=rect3) # 获取并输出所有周长 fig_container.get_perimeters() # 获取并输出所有面积 fig_container.get_areas() # 查看容器信息 print(fig_container)
关键优化点说明:
- 实现核心方法:
get_perimeters和get_areas不再需要额外参数,直接遍历self.figures中的Rectangle实例,调用对应的方法即可完成批量计算。
- 修正参数校验逻辑:
- 原
add_rectangle中的if width and height != None存在逻辑漏洞(比如宽为0时会被误判为无效),改为width is not None and height is not None做严格校验。
- 原
- 增强添加灵活性:
- 新增支持直接传入已创建的
Rectangle实例,让add_rectangle方法更通用。
- 新增支持直接传入已创建的
- 移除冗余属性:
- 删除了
num_figures属性,因为__len__方法已经可以通过len(self.figures)获取容器内的图形数量,无需额外维护。
- 删除了
- 优化字符串表示:
- 修改
Figures的__str__方法,显示容器内的矩形数量,让输出信息更有价值。
- 修改
内容的提问来源于stack exchange,提问作者Lina
相关产品推荐
相关产品推荐

