用Python做一个类的整体编程设计(可运行的)
时间: 2024-03-18 13:38:31 浏览: 22
以下是一个简单的 Python 类的整体编程设计示例,实现一个简单的矩形类:
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
def get_perimeter(self):
return 2 * (self.width + self.height)
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_width(self):
return self.width
def get_height(self):
return self.height
# 测试代码
rect = Rectangle(3, 4)
print("Width:", rect.get_width())
print("Height:", rect.get_height())
print("Area:", rect.get_area())
print("Perimeter:", rect.get_perimeter())
rect.set_width(5)
rect.set_height(6)
print("Width:", rect.get_width())
print("Height:", rect.get_height())
print("Area:", rect.get_area())
print("Perimeter:", rect.get_perimeter())
```
在上面的代码中,我们定义了一个矩形类 Rectangle,它有两个成员变量 width 和 height,分别表示矩形的宽和高。我们在构造函数 `__init__` 中初始化这两个变量,并提供了一些公共方法来获取和设置这两个变量。其中 `get_area` 和 `get_perimeter` 方法分别用于计算矩形的面积和周长。
在测试代码中,我们创建了一个 Rectangle 对象 rect,并输出了它的宽、高、面积和周长。然后我们调用了 `set_width` 和 `set_height` 方法来修改矩形的宽和高,并再次输出了它的宽、高、面积和周长。
运行该程序,将输出如下结果:
```
Width: 3
Height: 4
Area: 12
Perimeter: 14
Width: 5
Height: 6
Area: 30
Perimeter: 22
```
这个例子演示了如何创建一个简单的 Python 类,并使用它的对象来进行计算。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)