写出简易图书管理系统的代码
时间: 2024-08-13 15:07:40 浏览: 47
用c++面向对象实现一个简易的图书管理系统
5星 · 资源好评率100%
编写一个简单的图书管理系统,我们可以使用Python的面向对象编程(OOP)来实现。这里是一个基本的结构,假设我们主要关注书籍的基本信息(如标题、作者和出版年份),以及添加、删除和查询图书的功能。注意,这个例子不会包含图形用户界面(GUI),通常会用在命令行环境中。
```python
class Book:
def __init__(self, title, author, publication_year):
self.title = title
self.author = author
self.publication_year = publication_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)
break
def search_book(self, title):
found_books = [book for book in self.books if book.title == title]
if found_books:
return found_books
else:
return "Book not found."
# 使用示例
library = Library()
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 1960)
library.add_book(book1)
library.add_book(book2)
print("Library:")
books = library.search_book("To Kill a Mockingbird")
if books:
for book in books:
print(f"{book.title} by {book.author}, published: {book.publication_year}")
else:
print(books)
# 删除一本书
library.remove_book("The Great Gatsby")
# 再次搜索
books = library.search_book("The Great Gatsby")
print("After removal:")
if books:
print("Book not found.")
else:
print("Book removed successfully.")
```
阅读全文