定义一个Rectangle类,包含长和宽属性,以及计算面积和周长 的方法。创建Rectangle类的实例,并调用其方法.
时间: 2024-12-17 22:35:41 浏览: 11
当然可以。首先,我们定义一个名为`Rectangle`的类,它有两个属性`length`(长度)和`width`(宽度),并为这两个属性提供getter和setter方法。同时,我们将添加两个方法`calculate_area()`用于计算矩形的面积,`calculate_perimeter()`用于计算矩形的周长。
```python
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
# Getter and Setter methods
@property
def length(self):
return self._length
@length.setter
def length(self, value):
if value <= 0:
raise ValueError("Length must be a positive number")
self._length = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value <= 0:
raise ValueError("Width must be a positive number")
self._width = value
# Methods to calculate area and perimeter
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
# Creating an instance of the Rectangle class
my_rectangle = Rectangle(5, 3)
# Calling the methods
area = my_rectangle.calculate_area()
perimeter = my_rectangle.calculate_perimeter()
print(f"Area: {area}")
print(f"Perimeter: {perimeter}")
阅读全文