定义一个 Student 类,其中包含学号、姓名、成绩数据成员。建立若干个 Student 类 对象,将它们保存到文件 Record.dat 中,然后显示文件中的内容。
时间: 2023-11-28 13:51:09 浏览: 105
以下是一个示例代码,实现了上述要求:
```python
import pickle
class Student:
def __init__(self, num, name, score):
self.num = num
self.name = name
self.score = score
def __str__(self):
return f"学号:{self.num}\t姓名:{self.name}\t成绩:{self.score}"
# 创建若干个 Student 对象
students = [
Student("001", "张三", 90),
Student("002", "李四", 85),
Student("003", "王五", 92)
]
# 将对象保存到文件 Record.dat 中
with open("Record.dat", "wb") as f:
pickle.dump(students, f)
# 从文件中读取对象并显示内容
with open("Record.dat", "rb") as f:
data = pickle.load(f)
for student in data:
print(student)
```
运行结果如下:
```
学号:001 姓名:张三 成绩:90
学号:002 姓名:李四 成绩:85
学号:003 姓名:王五 成绩:92
```
在上面的代码中,我们定义了一个 `Student` 类,其中包含学号、姓名、成绩数据成员。然后,我们创建了三个 `Student` 类的对象,并将它们保存到名为 `Record.dat` 的文件中。
最后,我们从文件中读取对象,并通过 `__str__` 方法将其内容打印出来。注意,在读取数据时,我们使用了 `pickle` 模块来进行序列化和反序列化。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)