todo.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """
  2. 核心Todo类,负责待办事项的业务逻辑
  3. """
  4. from datetime import datetime
  5. from typing import List, Optional, Dict
  6. class TodoItem:
  7. """待办事项数据模型"""
  8. def __init__(self, id: int, title: str, completed: bool = False,
  9. created_at: Optional[str] = None):
  10. self.id = id
  11. self.title = title
  12. self.completed = completed
  13. self.created_at = created_at or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  14. def to_dict(self) -> Dict:
  15. """转换为字典格式"""
  16. return {
  17. "id": self.id,
  18. "title": self.title,
  19. "completed": self.completed,
  20. "created_at": self.created_at
  21. }
  22. @classmethod
  23. def from_dict(cls, data: Dict) -> 'TodoItem':
  24. """从字典创建TodoItem对象"""
  25. return cls(
  26. id=data["id"],
  27. title=data["title"],
  28. completed=data.get("completed", False),
  29. created_at=data.get("created_at")
  30. )
  31. def __repr__(self) -> str:
  32. status = "✓" if self.completed else " "
  33. return f"[{status}] {self.id}. {self.title}"
  34. class Todo:
  35. """待办事项管理类"""
  36. def __init__(self):
  37. self.items: List[TodoItem] = []
  38. self.next_id: int = 1
  39. def add(self, title: str) -> TodoItem:
  40. """添加待办事项"""
  41. if not title or not title.strip():
  42. raise ValueError("待办事项标题不能为空")
  43. item = TodoItem(id=self.next_id, title=title.strip())
  44. self.items.append(item)
  45. self.next_id += 1
  46. return item
  47. def delete(self, item_id: int) -> bool:
  48. """删除待办事项"""
  49. for i, item in enumerate(self.items):
  50. if item.id == item_id:
  51. self.items.pop(i)
  52. return True
  53. return False
  54. def complete(self, item_id: int) -> bool:
  55. """标记待办事项为完成"""
  56. item = self.get_by_id(item_id)
  57. if item:
  58. item.completed = True
  59. return True
  60. return False
  61. def uncomplete(self, item_id: int) -> bool:
  62. """标记待办事项为未完成"""
  63. item = self.get_by_id(item_id)
  64. if item:
  65. item.completed = False
  66. return True
  67. return False
  68. def get_by_id(self, item_id: int) -> Optional[TodoItem]:
  69. """根据ID获取待办事项"""
  70. for item in self.items:
  71. if item.id == item_id:
  72. return item
  73. return None
  74. def get_all(self) -> List[TodoItem]:
  75. """获取所有待办事项"""
  76. return self.items.copy()
  77. def get_pending(self) -> List[TodoItem]:
  78. """获取未完成的待办事项"""
  79. return [item for item in self.items if not item.completed]
  80. def get_completed(self) -> List[TodoItem]:
  81. """获取已完成的待办事项"""
  82. return [item for item in self.items if item.completed]
  83. def clear_completed(self) -> int:
  84. """清除所有已完成的待办事项,返回清除的数量"""
  85. completed_count = len(self.get_completed())
  86. self.items = [item for item in self.items if not item.completed]
  87. return completed_count
  88. def to_dict(self) -> Dict:
  89. """转换为字典格式用于存储"""
  90. return {
  91. "todos": [item.to_dict() for item in self.items],
  92. "next_id": self.next_id
  93. }
  94. def from_dict(self, data: Dict):
  95. """从字典加载数据"""
  96. self.items = [TodoItem.from_dict(item_data) for item_data in data.get("todos", [])]
  97. self.next_id = data.get("next_id", 1)