python图书管理类与对象
时间: 2023-09-21 17:03:02 浏览: 106
图书管理系统类和对象的分析
图书管理系统是一个典型的面向对象的应用程序,使用Python语言实现时可以采用类与对象的方式进行设计。
首先,我们可以定义一个 `Book` 类来表示一本书,其中包含属性如书名、作者、出版社、出版时间等信息,以及一些方法如获取书名、获取作者等。示例代码如下:
```python
class Book:
def __init__(self, title, author, publisher, publish_date):
self.title = title
self.author = author
self.publisher = publisher
self.publish_date = publish_date
def get_title(self):
return self.title
def get_author(self):
return self.author
def get_publisher(self):
return self.publisher
def get_publish_date(self):
return self.publish_date
```
接下来,我们可以定义一个 `Library` 类来表示一个图书馆,其中包含属性如馆名、馆长、馆内藏书数量等信息,以及一些方法如添加图书、删除图书、查找图书等。示例代码如下:
```python
class Library:
def __init__(self, name, curator):
self.name = name
self.curator = curator
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def find_book_by_title(self, title):
for book in self.books:
if book.get_title() == title:
return book
return None
def find_book_by_author(self, author):
author_books = []
for book in self.books:
if book.get_author() == author:
author_books.append(book)
return author_books
```
最后,我们可以编写一个测试程序,创建一个图书馆对象,添加一些书籍,然后测试查找功能。示例代码如下:
```python
if __name__ == '__main__':
library = Library('My Library', 'John Smith')
book1 = Book('Python Programming', 'Guido van Rossum', 'O\'Reilly Media', '2010-01-01')
book2 = Book('Data Science', 'John Doe', 'Wiley', '2015-06-01')
book3 = Book('Deep Learning', 'Andrew Ng', 'MIT Press', '2017-12-01')
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
print(library.find_book_by_title('Data Science').get_author()) # John Doe
print([book.get_title() for book in library.find_book_by_author('Guido van Rossum')]) # ['Python Programming']
```
以上就是一个简单的Python图书管理类与对象的实现示例。
阅读全文