编写一个图书管理系统
时间: 2023-09-06 16:07:35 浏览: 39
好的,下面是一个简单的图书管理系统的代码示例:
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
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(f"{book.title} by {book.author} (ISBN: {book.isbn})")
library = Library()
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "9780141182636")
book2 = Book("To Kill a Mockingbird", "Harper Lee", "9780446310789")
library.add_book(book1)
library.add_book(book2)
while True:
print("Enter 1 to add a book")
print("Enter 2 to remove a book")
print("Enter 3 to search for a book")
print("Enter 4 to display all books")
print("Enter 0 to exit")
choice = input("Enter your choice: ")
if choice == "1":
title = input("Enter the title of the book: ")
author = input("Enter the author of the book: ")
isbn = input("Enter the ISBN of the book: ")
new_book = Book(title, author, isbn)
library.add_book(new_book)
print("Book added successfully!")
elif choice == "2":
title = input("Enter the title of the book: ")
book = library.search_book(title)
if book:
library.remove_book(book)
print("Book removed successfully!")
else:
print("Book not found.")
elif choice == "3":
title = input("Enter the title of the book: ")
book = library.search_book(title)
if book:
print(f"{book.title} by {book.author} (ISBN: {book.isbn})")
else:
print("Book not found.")
elif choice == "4":
library.display_books()
elif choice == "0":
break
else:
print("Invalid choice. Try again.")
```
这个系统使用了两个类,一个是 `Book`,用于表示一本书,另一个是 `Library`,用于表示整个图书馆。`Library` 类有四个方法:`add_book` 用于添加一本书,`remove_book` 用于删除一本书,`search_book` 用于搜索一本书,`display_books` 用于展示所有的书。
这个系统还有一个简单的交互界面,用户可以通过输入数字来进行不同的操作。例如,输入 1 可以添加一本新书,输入 2 可以删除一本书,输入 3 可以搜索一本书,输入 4 可以展示所有书,输入 0 可以退出系统。