用python写一个图书管理系统
时间: 2023-06-25 17:06:30 浏览: 124
好的,以下是一个简单的图书管理系统的Python代码,其中包括添加图书、删除图书、查找图书和展示所有图书的功能:
```python
class Book:
def __init__(self, title, author, genre, year):
self.title = title
self.author = author
self.genre = genre
self.year = year
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"{book.title} has been removed from the library.")
return
print(f"{title} is not in the library.")
def find_book(self, title):
for book in self.books:
if book.title == title:
print(f"{book.title} by {book.author} ({book.year}) - {book.genre}")
return
print(f"{title} is not in the library.")
def display_books(self):
if len(self.books) == 0:
print("The library is empty.")
return
print("Books in the library:")
for book in self.books:
print(f"{book.title} by {book.author} ({book.year}) - {book.genre}")
# example usage
library = Library()
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "Classic", 1925)
book2 = Book("To Kill a Mockingbird", "Harper Lee", "Classic", 1960)
book3 = Book("1984", "George Orwell", "Dystopian", 1949)
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
library.display_books()
library.find_book("The Great Gatsby")
library.remove_book("To Kill a Mockingbird")
library.display_books()
```
运行结果如下:
```
Books in the library:
The Great Gatsby by F. Scott Fitzgerald (1925) - Classic
To Kill a Mockingbird by Harper Lee (1960) - Classic
1984 by George Orwell (1949) - Dystopian
The Great Gatsby by F. Scott Fitzgerald (1925) - Classic
To Kill a Mockingbird has been removed from the library.
Books in the library:
The Great Gatsby by F. Scott Fitzgerald (1925) - Classic
1984 by George Orwell (1949) - Dystopian
```