python写定义一个产品类Book表示图书库存类,该类有三个数据成员:name, publisher, price, count,分别表示该图书的书名(字符串型)、出版社(字符串型)、单价(小数类型)、库存数量(整数类型),通过构造函数传值进行初始化。图书的初始信息存储在books.txt文件中,每行表示一种图书,每行有四列分别表示产品的四个信息。要求从文件读取所有书籍信息,保存在列表中,按出版社和库存量排序,保存到文件。请根据以下给出的主函数代码完善整个程序代码。 def main(): booklist=[] loadBook(booklist) sortBook(booklist) saveBook(booklist) main()
时间: 2023-05-28 07:02:12 浏览: 126
Python数据类(Data Classes):简化类定义的现代方法
class Book:
def __init__(self, name, publisher, price, count):
self.name = name
self.publisher = publisher
self.price = price
self.count = count
def loadBook(booklist):
with open('books.txt', 'r') as file:
for line in file:
name, publisher, price, count = line.strip().split(' ')
book = Book(name, publisher, float(price), int(count))
booklist.append(book)
def saveBook(booklist):
with open('sorted_books.txt', 'w') as file:
for book in booklist:
file.write(f'{book.name} {book.publisher} {book.price} {book.count}\n')
def sortBook(booklist):
booklist.sort(key=lambda x: (x.publisher, x.count), reverse=True)
def main():
booklist = []
loadBook(booklist)
sortBook(booklist)
saveBook(booklist)
if __name__ == '__main__':
main()
阅读全文