请你把以上代码重新写一下,有语法错误
时间: 2024-10-26 20:03:11 浏览: 13
根据您提供的文档内容,我为您整理了一个基于 Python 的图书管理系统的示例代码。请注意,此代码已尽量遵循您的需求进行了编写,并加入了适当的异常处理以增强其健壮性。以下是完整的代码:
```python
import json
from typing import List, Optional
class Book:
def __init__(self, book_id: int, title: str, author: str, year: int):
self.__book_id = book_id
self.__title = title
self.__author = author
self.__year = year
self.__is_borrowed = False
@property
def id(self) -> int:
return self.__book_id
@property
def title(self) -> str:
return self.__title
@property
def author(self) -> str:
return self.__author
@property
def year(self) -> int:
return self.__year
@property
def is_borrowed(self) -> bool:
return self.__is_borrowed
def set_is_borrowed(self, value: bool):
self.__is_borrowed = value
def display_info(self):
print(f"ID: {self.__book_id}, Title: {self.__title}, Author: {self.__author}, Year: {self.__year}")
class Library:
def __init__(self, file_path: str = "library_data.json"):
self.file_path = file_path
self.books: List[Book] = []
self.load_books()
def add_book(self, book: Book):
if any(b.id == book.id for b in self.books):
raise ValueError("A book with this ID already exists.")
self.books.append(book)
self.save_books()
print(f"Book '{book.title}' added successfully.")
def remove_book(self, book_id: int):
book_to_remove = next((b for b in self.books if b.id == book_id), None)
if not book_to_remove:
raise ValueError("No book found with the given ID.")
self.books.remove(book_to_remove)
self.save_books()
print(f"Book with ID {book_id} removed successfully.")
def update_book(self, book_id: int, **kwargs):
book_to_update = next((b for b in self.books if b.id == book_id), None)
if not book_to_update:
raise ValueError("No book found with the given ID.")
for key, value in kwargs.items():
setattr(book_to_update, f"_{key}", value)
self.save_books()
print(f"Book with ID {book_id} updated successfully.")
def find_book(self, book_id: int) -> Optional[Book]:
return next((b for b in self.books if b.id == book_id), None)
def list_all_books(self):
for book in self.books:
book.display_info()
def borrow_book(self, book_id: int):
book = self.find_book(book_id)
if not book:
raise ValueError("No book found with the given ID.")
if book.is_borrowed:
raise ValueError("This book is currently borrowed by someone else.")
book.set_is_borrowed(True)
self.save_books()
print(f"Book with ID {book_id} has been borrowed.")
def return_book(self, book_id: int):
book = self.find_book(book_id)
if not book:
raise ValueError("No book found with the given ID.")
if not book.is_borrowed:
raise ValueError("This book was not borrowed before.")
book.set_is_borrowed(False)
self.save_books()
print(f"Book with ID {book_id} has been returned.")
def load_books(self):
try:
with open(self.file_path, 'r') as file:
data = json.load(file)
self.books = [Book(**book_data) for book_data in data]
except FileNotFoundError:
pass # File does not exist, start with an empty library.
except Exception as e:
print(f"Error loading books from file: {e}")
def save_books(self):
try:
with open(self.file_path, 'w') as file:
data = [{"book_id": b.id, "title": b.title, "author": b.author, "year": b.year, "is_borrowed": b.is_borrowed} for b in self.books]
json.dump(data, file, indent=4)
except Exception as e:
print(f"Error saving books to file: {e}")
def main():
library = Library()
while True:
print("\n1. Add Book\n2. Remove Book\n3. Update Book\n4. Find Book\n5. Borrow Book\n6. Return Book\n7. List All Books\n8. Exit")
choice = input("Enter your choice: ")
if choice == '1':
book_id = int(input("Enter book ID: "))
title = input("Enter book title: ")
author = input("Enter book author: ")
year = int(input("Enter publication year: "))
book = Book(book_id, title, author, year)
library.add_book(book)
elif choice == '2':
book_id = int(input("Enter book ID to remove: "))
library.remove_book(book_id)
elif choice == '3':
book_id = int(input("Enter book ID to update: "))
field = input("Enter field to update (title/author/year): ")
new_value = input("Enter new value: ")
library.update_book(book_id, **{field: new_value})
elif choice == '4':
book_id = int(input("Enter book ID to find: "))
book = library.find_book(book_id)
if book:
book.display_info()
else:
print("No book found with the given ID.")
elif choice == '5':
book_id = int(input("Enter book ID to borrow: "))
library.borrow_book(book_id)
elif choice == '6':
book_id = int(input("Enter book ID to return: "))
library.return_book(book_id)
elif choice == '7':
library.list_all_books()
elif choice == '8':
break
else:
print("Invalid choice, please try again.")
if __name__ == "__main__":
main()
```
### 关键点说明:
1. **类设计**:
- `Book` 类封装了图书的信息,包括 ID、标题、作者、出版年份和是否被借出状态。
- `Library` 类管理图书的集合,提供了添加、删除、更新、查找、借阅和归还等功能。
2. **文件管理**:
- 使用 JSON 文件进行数据的持久化存储。`load_books` 和 `save_books` 方法分别用于加载和保存图书数据。
3. **异常处理**:
- 在关键操作中加入了异常处理,确保程序在遇到错误时能够给出合理的提示。
4. **用户交互**:
- 提供了一个简单的命令行界面,用户可以通过输入数字选择不同的操作。
希望这段代码能满足您的需求!如果有任何进一步的问题或需要调整的地方,请告诉我。
阅读全文