请把这些都写到一个.py文件里
时间: 2024-10-25 19:15:48 浏览: 14
对python同一个文件夹里面不同.py文件的交叉引用方法详解
当然可以!下面是一个完整的 `book_management_system.py` 文件,实现了您所描述的图书管理系统:
```python
import json
import os
class Book:
def __init__(self, id, title, author, publication_year):
self.__id = id
self.__title = title
self.__author = author
self.__publication_year = publication_year
self.__is_borrowed = False
def get_id(self):
return self.__id
def get_title(self):
return self.__title
def get_author(self):
return self.__author
def get_publication_year(self):
return self.__publication_year
def is_borrowed(self):
return self.__is_borrowed
def set_title(self, title):
self.__title = title
def set_author(self, author):
self.__author = author
def set_publication_year(self, publication_year):
self.__publication_year = publication_year
def borrow_book(self):
if not self.__is_borrowed:
self.__is_borrowed = True
return True
else:
raise ValueError("The book is already borrowed.")
def return_book(self):
if self.__is_borrowed:
self.__is_borrowed = False
return True
else:
raise ValueError("The book is not currently borrowed.")
def display_info(self):
print(f"ID: {self.__id}, Title: {self.__title}, Author: {self.__author}, Publication Year: {self.__publication_year}, Borrowed: {self.__is_borrowed}")
class Library:
def __init__(self, file_path="library_data.json"):
self.file_path = file_path
self.books = []
self.load_books()
def load_books(self):
if os.path.exists(self.file_path):
with open(self.file_path, 'r') as f:
data = json.load(f)
for book_data in data:
book = Book(**book_data)
self.books.append(book)
def save_books(self):
with open(self.file_path, 'w') as f:
data = [book.__dict__ for book in self.books]
json.dump(data, f, indent=4)
def add_book(self, book):
self.books.append(book)
self.save_books()
print("Book added successfully.")
def remove_book(self, id):
for book in self.books:
if book.get_id() == id:
self.books.remove(book)
self.save_books()
print("Book removed successfully.")
return
raise ValueError("Book not found.")
def update_book(self, id, **kwargs):
for book in self.books:
if book.get_id() == id:
for key, value in kwargs.items():
if hasattr(book, f"set_{key}"):
getattr(book, f"set_{key}")(value)
self.save_books()
print("Book updated successfully.")
return
raise ValueError("Book not found.")
def find_book(self, id):
for book in self.books:
if book.get_id() == id:
return book
raise ValueError("Book not found.")
def list_all_books(self):
for book in self.books:
book.display_info()
def borrow_book(self, id):
book = self.find_book(id)
if book.borrow_book():
self.save_books()
print("Book borrowed successfully.")
def return_book(self, id):
book = self.find_book(id)
if book.return_book():
self.save_books()
print("Book returned successfully.")
def main():
library = Library()
while True:
print("\nLibrary Management System")
print("1. Add Book")
print("2. Remove Book")
print("3. Update Book")
print("4. Find Book")
print("5. List All Books")
print("6. Borrow Book")
print("7. Return Book")
print("8. Exit")
choice = input("Enter your choice: ")
try:
if choice == "1":
id = input("Enter ID: ")
title = input("Enter Title: ")
author = input("Enter Author: ")
publication_year = int(input("Enter Publication Year: "))
book = Book(id, title, author, publication_year)
library.add_book(book)
elif choice == "2":
id = input("Enter ID: ")
library.remove_book(id)
elif choice == "3":
id = input("Enter ID: ")
title = input("Enter new Title (leave blank to skip): ")
author = input("Enter new Author (leave blank to skip): ")
publication_year = input("Enter new Publication Year (leave blank to skip): ")
kwargs = {}
if title:
kwargs['title'] = title
if author:
kwargs['author'] = author
if publication_year:
kwargs['publication_year'] = int(publication_year)
library.update_book(id, **kwargs)
elif choice == "4":
id = input("Enter ID: ")
book = library.find_book(id)
book.display_info()
elif choice == "5":
library.list_all_books()
elif choice == "6":
id = input("Enter ID: ")
library.borrow_book(id)
elif choice == "7":
id = input("Enter ID: ")
library.return_book(id)
elif choice == "8":
break
else:
print("Invalid choice. Please try again.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
```
### 说明
1. **Book 类**:包含图书的基本属性和方法,并且属性被私有化。
2. **Library 类**:管理图书的集合,实现添加、删除、修改、查询图书以及图书的借阅与归还功能。
3. **文件管理**:使用 JSON 格式进行数据的持久化存储。
4. **异常处理**:在关键操作中加入了异常处理机制。
5. **用户交互**:设计了一个简单的命令行界面(CLI),允许用户通过输入指令来管理图书和借阅活动。
您可以将上述代码保存为 `book_management_system.py` 并运行它。希望这能满足您的需求!如果有任何进一步的问题,请随时告诉我。
阅读全文