用python写一个图书管理系统
时间: 2023-07-18 11:38:13 浏览: 90
好的,下面是一个简单的图书管理系统的Python代码示例:
```python
class Book:
def __init__(self, book_id, title, author, num_copies):
self.book_id = book_id
self.title = title
self.author = author
self.num_copies = num_copies
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def search_book(self, title):
for book in self.books:
if book.title == title:
return book
return None
def display_books(self):
for book in self.books:
print("Book ID:", book.book_id)
print("Title:", book.title)
print("Author:", book.author)
print("Number of copies:", book.num_copies)
if __name__ == '__main__':
library = Library()
book1 = Book(1, "The Great Gatsby", "F. Scott Fitzgerald", 2)
book2 = Book(2, "To Kill a Mockingbird", "Harper Lee", 1)
book3 = Book(3, "1984", "George Orwell", 3)
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
library.display_books()
search_title = "To Kill a Mockingbird"
found_book = library.search_book(search_title)
if found_book:
print("Book found:")
print("Book ID:", found_book.book_id)
print("Title:", found_book.title)
print("Author:", found_book.author)
print("Number of copies:", found_book.num_copies)
else:
print("Book not found.")
```
这个代码示例定义了两个类:`Book` 和 `Library`。`Book` 类表示一本书,包含书籍的 ID、标题、作者和数量。`Library` 类表示图书馆,包含一个书籍列表和一些方法,如添加书籍、删除书籍、搜索书籍和显示所有书籍。
在 `main` 函数中,我们创建了一个图书馆对象,并向其中添加了三本书。然后,我们显示了所有书籍,并搜索了一本名为 “To Kill a Mockingbird” 的书籍,打印出了它的详细信息。
阅读全文