Python 矩形类:创建、调整大小和私有方法
使用 Python 创建一个名为'Rectangle'的类,包含调整大小功能
本教程将指导你如何在 Python 中创建一个名为'Rectangle'的类,该类具有'width'和'height'属性,并提供一个名为'resize()'的实例方法用于调整矩形的大小。为了计算新的矩形尺寸,我们还将使用一个私有方法'_calculate_new_dimensions()'。
代码实现
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)
# 使用示例
rectangle = Rectangle(10, 20)
rectangle.resize(15, 25)
print(rectangle.width, rectangle.height) # 输出:15.0 25.0
代码解释
- 类定义:
class Rectangle:定义了一个名为'Rectangle'的类。 - 构造函数:
__init__(self, width, height)是构造函数,用于初始化矩形的宽度和高度。 - resize()方法:
resize(self, new_width, new_height)方法接受新的宽度和高度作为参数,并使用私有方法'_calculate_new_dimensions()'计算新的尺寸。 - 私有方法:
_calculate_new_dimensions(self, new_width, new_height)是一个私有方法,用于计算新的矩形尺寸,确保宽高比例保持一致。 - 使用示例: 代码创建了一个名为'rectangle'的'Rectangle'对象,初始宽度为10,高度为20。然后,使用'resize()'方法将其调整为宽度15,高度25,并打印出调整后的尺寸。
总结
本教程演示了如何在 Python 中使用类、属性、方法和私有方法来创建和操作矩形对象。通过使用私有方法来计算新的尺寸,我们可以确保代码的可读性和可维护性。
原文地址: https://www.cveoy.top/t/topic/mY7L 著作权归作者所有。请勿转载和采集!