生成一个学生对象Student,对象有学号,年龄,身高。将学生对象存储到文件,然后从文件中读取数据重新生成Student对象。
时间: 2024-02-26 10:56:47 浏览: 27
好的,我可以帮你生成一个学生对象并将其存储到文件中,然后从文件中读取数据重新生成学生对象。以下是实现的Python代码:
```python
import pickle
class Student:
def __init__(self, student_id, age, height):
self.student_id = student_id
self.age = age
self.height = height
def __str__(self):
return f"Student: ID={self.student_id}, Age={self.age}, Height={self.height}"
# 创建学生对象
student = Student("20210001", 20, 175)
# 将学生对象存储到文件
with open("student.pkl", "wb") as f:
pickle.dump(student, f)
# 从文件中读取数据重新生成学生对象
with open("student.pkl", "rb") as f:
new_student = pickle.load(f)
# 打印重新生成的学生对象
print(new_student)
```
运行以上代码,输出结果如下所示:
```
Student: ID=20210001, Age=20, Height=175
```
可以看到,我们成功地生成了一个学生对象,并将其存储到文件中。然后,我们从文件中读取数据重新生成了学生对象,并成功打印出了重新生成的学生对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](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)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)