python设计一个矩形(Rectangle)类,具有宽度和高度两个属性,可以通过setter方法设置,也可以通过getter方法获取。设计一个方法计算矩形的面积和周长。请给出使用示例
时间: 2024-05-24 09:12:57 浏览: 64
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
def area(self):
return self._width * self._height
def perimeter(self):
return 2 * (self._width + self._height)
# 使用示例
rectangle = Rectangle(4, 5)
print(rectangle.width) # 4
print(rectangle.height) # 5
rectangle.width = 6
rectangle.height = 7
print(rectangle.width) # 6
print(rectangle.height) # 7
print(rectangle.area()) # 42
print(rectangle.perimeter()) # 26
阅读全文