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

    def resize(self, new_width, new_height):
        self.width, self.height = self._calculate_new_dimensions(new_width, new_height)

    def _calculate_new_dimensions(self, new_width, new_height):
        ratio_width = new_width / self.width
        ratio_height = new_height / self.height
        return (new_width, self.height * ratio_width) if ratio_width < ratio_height else (self.width * ratio_height, new_height)

# 使用示例
r = Rectangle(10, 5)
print(f"原始尺寸: width={r.width}, height={r.height}")  # 原始尺寸: width=10, height=5
r.resize(20, 3)
print(f"更改后尺寸: width={r.width}, height={r.height}")  # 更改后尺寸: width=6.0, height=3
用python创建一个名为 Rectangle 的类包含以下属性:width 和 height。创建一个实例方法 resize用于更改矩形的大小。在方法中使用私有方法 _calculate_new_dimensions 计算新的矩形尺寸。请给出使用示例

原文地址: https://www.cveoy.top/t/topic/bvhF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录