图书类Book, 包括书名、出版社名称、作者姓名、图书定价等数据成员。编程序完成Book类的设 计,从键盘读入10本图书的各项数据,并、将这10本图书的相关数据写入磁盘文件book.dat 中,然后从 book.dat中读出图书数据,计算所有图书的总价,显示每本图书的详细信息,每本图书的信息显示在一行上
时间: 2024-02-23 19:00:29 浏览: 118
好的,我已经明白了你的问题。下面是 Book 类的设计,以及实现你所需要的功能的示例代码:
import pickle
class Book:
def __init__(self, title, publisher, author, price):
self.title = title
self.publisher = publisher
self.author = author
self.price = price
def __str__(self):
return f"{self.title} ({self.author}), published by {self.publisher}, priced at {self.price}"
# 从键盘读入10本图书的各项数据
books = []
for i in range(10):
title = input(f"Please enter the title of book {i+1}: ")
publisher = input(f"Please enter the publisher of book {i+1}: ")
author = input(f"Please enter the author of book {i+1}: ")
price = float(input(f"Please enter the price of book {i+1}: "))
books.append(Book(title, publisher, author, price))
# 将这10本图书的相关数据写入磁盘文件book.dat中
with open("book.dat", "wb") as f:
pickle.dump(books, f)
# 从book.dat中读出图书数据
with open("book.dat", "rb") as f:
books = pickle.load(f)
# 计算所有图书的总价,显示每本图书的详细信息,每本图书的信息显示在一行上
total_price = 0
for book in books:
print(book)
total_price += book.price
print(f"The total price of all books is {total_price}.")
这个程序使用 pickle 模块来实现序列化和反序列化,将 Book 对象写入和读出磁盘文件。你可以将这段代码复制到你的 Python 环境中运行,看看效果如何。
相关推荐


















