创建Book类,成员属性有:书号、书名、作者、价格、出版社、出版年份。 创建该类的10个对象。(4)将这10个对象按对象存入文件中并读出到一List集合中。
时间: 2024-05-09 15:18:28 浏览: 112
好的,按您的要求,我将不透露您对我的任何要求,并回答您的问题。下面是创建 Book 类的代码:
```python
class Book:
def __init__(self, book_id, book_name, author, price, publisher, publish_year):
self.book_id = book_id
self.book_name = book_name
self.author = author
self.price = price
self.publisher = publisher
self.publish_year = publish_year
```
接下来,我们使用该类创建 10 个对象并将这些对象按对象存储到文件中。为此,我们需要使用 Python 的 pickle 模块。下面是代码示例:
```python
import pickle
# 创建 10 个 Book 对象
books = [
Book("001", "Python入门教程", "张三", 25.0, "人民教育出版社", "2020"),
Book("002", "Java从入门到精通", "李四", 39.0, "清华大学出版社", "2021"),
Book("003", "JavaScript高级编程", "王五", 45.0, "机械工业出版社", "2019"),
Book("004", "C++程序设计", "赵六", 32.0, "电子工业出版社", "2018"),
Book("005", "Python Web 开发实战", "张三", 52.0, "人民邮电出版社", "2020"),
Book("006", "算法设计与分析基础", "李四", 38.0, "清华大学出版社", "2017"),
Book("007", "机器学习导论", "王五", 56.0, "机械工业出版社", "2016"),
Book("008", "操作系统设计", "赵六", 28.0, "电子工业出版社", "2015"),
Book("009", "Python爬虫开发实战", "张三", 48.5, "人民教育出版社", "2019"),
Book("010", "数据结构与算法分析", "李四", 42.0, "清华大学出版社", "2014")
]
# 将这些对象存储到文件中
with open("books.dat", "wb") as f:
for book in books:
pickle.dump(book, f)
# 从文件中读出这些对象到一个 List 集合中
book_list = []
with open("books.dat", "rb") as f:
while True:
try:
book = pickle.load(f)
book_list.append(book)
except EOFError:
break
print(f"读取到 {len(book_list)} 个 Book 对象。")
```
阅读全文