请用python实现,类的方法也要写出来,不要用注释省略
时间: 2024-10-25 08:16:01 浏览: 13
robotframework调用python类方法-(五)RobotFramework基础。。。.pdf
好的,下面是基于您提供的需求,使用Python实现的一个简单图书管理系统。这个实现包括了`Book`类和`Library`类,并实现了文件管理和异常处理等功能。
### `book.py`
```python
import json
class Book:
def __init__(self, book_id, title, author, publication_year):
self.__book_id = book_id
self.__title = title
self.__author = author
self.__publication_year = publication_year
self.__is_borrowed = False
def get_book_id(self):
return self.__book_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, year):
self.__publication_year = year
def borrow_book(self):
if not self.__is_borrowed:
self.__is_borrowed = True
return True
return False
def return_book(self):
if self.__is_borrowed:
self.__is_borrowed = False
return True
return False
def to_dict(self):
return {
'book_id': self.__book_id,
'title': self.__title,
'author': self.__author,
'publication_year': self.__publication_year,
'is_borrowed': self.__is_borrowed
}
@classmethod
def from_dict(cls, data):
book = cls(data['book_id'], data['title'], data['author'], data['publication_year'])
book.__is_borrowed = data.get('is_borrowed', False)
return book
def __str__(self):
borrowed_status = "Borrowed" if self.__is_borrowed else "Available"
return f"ID: {self.__book_id}, Title: {self.__title}, Author: {self.__author}, Year: {self.__publication_year}, Status: {borrowed_status}"
```
### `library.py`
```python
import os
import json
from book import Book
class Library:
def __init__(self, file_path='books.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 file:
try:
data = json.load(file)
self.books = [Book.from_dict(book_data) for book_data in data]
except json.JSONDecodeError:
print("Failed to decode JSON file.")
else:
print(f"File {self.file_path} does not exist.")
def save_books(self):
with open(self.file_path, 'w') as file:
data = [book.to_dict() for book in self.books]
json.dump(data, file, indent=4)
def add_book(self, book):
self.books.append(book)
self.save_books()
print(f"Book '{book.get_title()}' added successfully.")
def remove_book(self, book_id):
for book in self.books:
if book.get_book_id() == book_id:
self.books.remove(book)
self.save_books()
print(f"Book with ID {book_id} removed successfully.")
return
print(f"Book with ID {book_id} not found.")
def update_book(self, book_id, **kwargs):
for book in self.books:
if book.get_book_id() == book_id:
for key, value in kwargs.items():
if hasattr(book, f'set_{key}'):
getattr(book, f'set_{key}')(value)
self.save_books()
print(f"Book with ID {book_id} updated successfully.")
return
print(f"Book with ID {book_id} not found.")
def find_book(self, book_id):
for book in self.books:
if book.get_book_id() == book_id:
return book
return None
def list_books(self):
if not self.books:
print("No books available in the library.")
return
for book in self.books:
print(book)
def borrow_book(self, book_id):
book = self.find_book(book_id)
if book:
if book.borrow_book():
self.save_books()
print(f"Book '{book.get_title()}' borrowed successfully.")
else:
print(f"Book '{book.get_title()}' is already borrowed.")
else:
print(f"Book with ID {book_id} not found.")
def return_book(self, book_id):
book = self.find_book(book_id)
if book:
if book.return_book():
self.save_books()
print(f"Book '{book.get_book()}' returned successfully.")
else:
print(f"Book '{book.get_title()}' was not borrowed.")
else:
print(f"Book with ID {book_id} not found.")
```
### `main.py`
```python
from library import Library
def main():
library = Library()
while True:
print("\nLibrary Management System")
print("1. Add Book")
print("2. Remove Book")
print("3. Update Book")
print("4. List Books")
print("5. Borrow Book")
print("6. Return Book")
print("7. Exit")
choice = input("Enter your choice: ")
if choice == '1':
book_id = input("Enter book ID: ")
title = input("Enter book title: ")
author = input("Enter book author: ")
publication_year = input("Enter publication year: ")
new_book = Book(book_id, title, author, publication_year)
library.add_book(new_book)
elif choice == '2':
book_id = input("Enter book ID to remove: ")
library.remove_book(book_id)
elif choice == '3':
book_id = input("Enter book ID to update: ")
title = input("Enter new title (leave blank to keep current): ")
author = input("Enter new author (leave blank to keep current): ")
publication_year = input("Enter new publication year (leave blank to keep current): ")
updates = {}
if title:
updates['title'] = title
if author:
updates['author'] = author
if publication_year:
updates['publication_year'] = publication_year
library.update_book(book_id, **updates)
elif choice == '4':
library.list_books()
elif choice == '5':
book_id = input("Enter book ID to borrow: ")
library.borrow_book(book_id)
elif choice == '6':
book_id = input("Enter book ID to return: ")
library.return_book(book_id)
elif choice == '7':
print("Exiting the system.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
```
### 测试代码
为了验证系统的正确性,可以编写一些单元测试:
### `test_library.py`
```python
import unittest
from library import Library
from book import Book
class TestLibrary(unittest.TestCase):
def setUp(self):
self.library = Library(file_path='test_books.json')
self.book1 = Book('1', 'Book One', 'Author A', 2000)
self.book2 = Book('2', 'Book Two', 'Author B', 2001)
self.library.add_book(self.book1)
self.library.add_book(self.book2)
def tearDown(self):
if os.path.exists('test_books.json'):
os.remove('test_books.json')
def test_add_book(self):
book3 = Book('3', 'Book Three', 'Author C', 2002)
self.library.add_book(book3)
self.assertEqual(len(self.library.books), 3)
def test_remove_book(self):
self.library.remove_book('1')
self.assertEqual(len(self.library.books), 1)
def test_update_book(self):
self.library.update_book('1', title='Updated Title')
book = self.library.find_book('1')
self.assertEqual(book.get_title(), 'Updated Title')
def test_find_book(self):
book = self.library.find_book('1')
self.assertIsNotNone(book)
self.assertEqual(book.get_title(), 'Book One')
def test_list_books(self):
books = self.library.books
self.assertEqual(len(books), 2)
self.assertIn(self.book1, books)
self.assertIn(self.book2, books)
def test_borrow_book(self):
self.library.borrow_book('1')
book = self.library.find_book('1')
self.assertTrue(book.is_borrowed())
def test_return_book(self):
self.library.borrow_book('1')
self.library.return_book('1')
book = self.library.find_book('1')
self.assertFalse(book.is_borrowed())
if __name__ == '__main__':
unittest.main()
```
以上代码实现了一个基本的图书管理系统,包括图书的添加、删除、更新、查询、借阅和归还功能,并且支持数据的持久化存储和异常处理。希望这能满足您的需求!如果有任何进一步的问题,请随时告诉我。
阅读全文