用python写一个图书管理系统
时间: 2023-07-18 18:13:00 浏览: 98
好的,下面是一个简单的图书管理系统的 Python 代码示例:
```python
class Book:
def __init__(self, name, author, year):
self.name = name
self.author = author
self.year = year
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book_name):
for book in self.books:
if book.name == book_name:
self.books.remove(book)
print(f"{book_name} has been removed from the library.")
return
print(f"{book_name} is not in the library.")
def search_book(self, book_name):
for book in self.books:
if book.name == book_name:
print(f"{book.name} by {book.author}, published in {book.year}")
return
print(f"{book_name} is not in the library.")
def display_books(self):
for book in self.books:
print(f"{book.name} by {book.author}, published in {book.year}")
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)
library.display_books()
library.search_book("The Great Gatsby")
library.remove_book("To Kill a Mockingbird")
library.display_books()
```
这个示例代码定义了两个类:`Book` 和 `Library`。`Book` 类表示图书,包含图书名称、作者和出版年份;`Library` 类表示图书馆,包含一个列表 `books`,可以添加、删除、搜索和显示图书。
在主程序中,我们实例化一个 `Library` 对象,并向其添加两本图书。然后,我们展示图书馆中所有的图书,搜索特定的图书,删除另外一本图书,最后再次展示图书馆中所有的图书。
阅读全文