设计一个rectangle类
时间: 2023-05-13 16:06:10 浏览: 86
好的,设计一个rectangle类,可以包含以下属性和方法:
属性:
- width: 矩形的宽度
- height: 矩形的高度
方法:
- __init__(self, width, height): 构造函数,初始化矩形的宽度和高度
- area(self): 计算矩形的面积
- perimeter(self): 计算矩形的周长
- is_square(self): 判断矩形是否为正方形
完整代码如下:
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def is_square(self):
return self.width == self.height
```
使用示例:
```python
rect = Rectangle(5, 10)
print(rect.area()) # 50
print(rect.perimeter()) # 30
print(rect.is_square()) # False
square = Rectangle(5, 5)
print(square.area()) # 25
print(square.perimeter()) # 20
print(square.is_square()) # True
```