编写Python图书管理系统代码
时间: 2024-10-14 20:11:27 浏览: 43
编写一个简单的Python图书管理系统涉及到几个主要组件:书籍模型(Book)、数据库操作、用户界面以及可能的一些基本的业务逻辑。以下是一个简化的例子,使用SQLite数据库和命令行接口:
```python
import sqlite3
from typing import List
class Book:
def __init__(self, title: str, author: str):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
class Library:
def __init__(self):
self.conn = sqlite3.connect('library.db')
self.cursor = self.conn.cursor()
self.cursor.execute('''CREATE TABLE IF NOT EXISTS books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL)''')
def add_book(self, title: str, author: str):
self.cursor.execute("INSERT INTO books (title, author) VALUES (?, ?)", (title, author))
self.conn.commit()
def list_books(self) -> List[Book]:
self.cursor.execute("SELECT * FROM books")
rows = self.cursor.fetchall()
return [Book(*row) for row in rows]
def remove_book(self, title: str):
self.cursor.execute("DELETE FROM books WHERE title=?", (title,))
self.conn.commit()
# 假设我们有一个命令行界面
def main():
library = Library()
while True:
print("\nOptions:")
print("1. Add a book")
print("2. List books")
print("3. Remove a book")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
title = input("Title: ")
author = input("Author: ")
library.add_book(title, author)
elif choice == '2':
for book in library.list_books():
print(book)
elif choice == '3':
title = input("Title of the book to remove: ")
library.remove_book(title)
elif choice == '4':
break
else:
print("Invalid choice. Try again.")
if __name__ == "__main__":
main()
```
在这个例子中,`Library`类负责管理数据库中的书籍信息,包括添加新书、列出所有书和删除指定的书。用户可以通过命令行选择相应的选项进行操作。
阅读全文
相关推荐

















