Python 类定义 图书管理系统
时间: 2024-12-04 20:12:31 浏览: 19
好的,以下是一个简单的Python类定义,用于图书管理系统的示例。这个示例包括几个类,如`Book`、`User`和`Library`,以及它们的基本方法和属性。
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.is_available = True
def __str__(self):
return f"《{self.title}》 by {self.author}, ISBN: {self.isbn}"
def borrow_book(self):
if self.is_available:
self.is_available = False
return True
else:
return False
def return_book(self):
self.is_available = True
class User:
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
self.borrowed_books = []
def borrow_book(self, book):
if book.borrow_book():
self.borrowed_books.append(book)
print(f"{self.name} 成功借阅了 {book.title}")
else:
print(f"{book.title} 已经被借走了")
def return_book(self, book):
if book in self.borrowed_books:
book.return_book()
self.borrowed_books.remove(book)
print(f"{self.name} 成功归还了 {book.title}")
else:
print(f"{self.name} 没有借阅过 {book.title}")
class Library:
def __init__(self):
self.books = []
self.users = []
def add_book(self, book):
self.books.append(book)
print(f"添加了新书: {book}")
def register_user(self, user):
self.users.append(user)
print(f"注册了新用户: {user.name}")
def find_book_by_title(self, title):
for book in self.books:
if book.title == title:
return book
return None
def find_user_by_id(self, user_id):
for user in self.users:
if user.user_id == user_id:
return user
return None
# 示例使用
library = Library()
# 添加书籍
library.add_book(Book("Python编程", "John Doe", "1234567890"))
library.add_book(Book("数据科学导论", "Jane Smith", "0987654321"))
# 注册用户
library.register_user(User("001", "Alice"))
library.register_user(User("002", "Bob"))
# 查找书籍
book = library.find_book_by_title("Python编程")
user = library.find_user_by_id("001")
# 借阅书籍
user.borrow_book(book)
# 归还书籍
user.return_book(book)
```
在这个示例中,`Book`类表示一本书,`User`类表示一个用户,`Library`类表示整个图书馆。`Library`类包含添加书籍、注册用户、查找书籍和用户的方法。`User`类包含借阅和归还书籍的方法。
阅读全文