4假设图书管的图书包含书名、编号、作者属性和出版社等属性读者包含姓名、ID和借书属性每位读者最多可以借6本书。编写程序列出某读者的借书情况
以下是一个Python示例程序,用于显示某个读者的借书情况:
class Book:
def __init__(self, title, number, author, publisher):
self.title = title
self.number = number
self.author = author
self.publisher = publisher
class Reader:
def __init__(self, name, id):
self.name = name
self.id = id
self.books = []
def borrow_book(self, book):
if len(self.books) >= 6:
print("You have borrowed the maximum number of books.")
else:
self.books.append(book)
print("You have borrowed the book", book.title)
def return_book(self, book):
if book in self.books:
self.books.remove(book)
print("You have returned the book", book.title)
else:
print("You have not borrowed the book", book.title)
def list_borrowed_books(self):
print("Borrowed books:")
for book in self.books:
print(book.title)
# 创建几本图书
book1 = Book("Python Programming", 123456, "John Smith", "O'Reilly Media")
book2 = Book("Data Structures and Algorithms", 789012, "Alice Johnson", "Addison-Wesley Professional")
book3 = Book("Artificial Intelligence", 345678, "Bob Brown", "MIT Press")
# 创建一个读者
reader1 = Reader("Tom", 1001)
# 借几本书
reader1.borrow_book(book1)
reader1.borrow_book(book2)
reader1.borrow_book(book3)
# 显示借的书
reader1.list_borrowed_books()
# 还书
reader1.return_book(book2)
# 再次显示借的书
reader1.list_borrowed_books()
以上程序创建了两个类,Book和Reader,分别表示图书和读者。每个图书对象包含书名、编号、作者和出版社等属性,每个读者对象包含姓名、ID和借书列表等属性。读者对象具有借书、还书和列出借书情况等方法。
在程序中,首先创建了几个图书对象和一个读者对象。然后,读者对象借了几本书,并显示了借的书。接着,读者对象还了一本书,并再次显示了借的书。
输出结果如下:
You have borrowed the book Python Programming
You have borrowed the book Data Structures and Algorithms
You have borrowed the book Artificial Intelligence
Borrowed books:
Python Programming
Data Structures and Algorithms
Artificial Intelligence
You have returned the book Data Structures and Algorithms
Borrowed books:
Python Programming
Artificial Intelligence
``
原文地址: https://www.cveoy.top/t/topic/fiIw 著作权归作者所有。请勿转载和采集!