Todo 列表 Manager
你将构建什么
Python TodoList 类那个添加, completes, 移除, and 列表任务, 使用 JSON 保存/加载 — mini 任务 manager.
学习目标
- 定义类 使用 __init__ and 实例方法
- Use 列表的 dictionaries 到存储任务
- Serialize and deserialize 使用 JSON 模块
- 筛选任务通过状态使用列表 comprehensions
前置要求
- 类 and 对象
- 列表 and dictionaries
- JSON handling
步骤
- 1
定义 TodoList 类
创建 TodoList 类使用 __init__ 那个 initializes 空列表的 任务. 每个任务是 dict 使用 'title' and '做' 键.
代码class TodoList: def __init__(self): self.tasks = [] def add(self, title): self.tasks.append({"title": title, "done": False}) print(f"Added: {title}")预期结果
todo = TodoList(); todo.添加('Buy milk') 添加任务 and prints confirmation.
- 2
添加完整 and 移除方法
添加完整(索引) 那个 marks 任务做, and 移除(索引) 那个删除任务. 包含边界检查.
代码def complete(self, index): if 0 <= index < len(self.tasks): self.tasks[index]["done"] = True print(f"Completed: {self.tasks[index]['title']}") def remove(self, index): if 0 <= index < len(self.tasks): removed = self.tasks.pop(index) print(f"Removed: {removed['title']}")预期结果
todo.完整(0) marks 首先任务做; todo.移除(0) 删除它.
- 3
添加 display and JSON 保存/加载
添加 display() 那个 prints 所有任务使用状态, and 保存(filename)/加载(filename) 那个 serialize 到/从 JSON.
代码def display(self): if not self.tasks: print("No tasks.") return for i, task in enumerate(self.tasks): status = "[x]" if task["done"] else "[ ]" print(f"{i}. {status} {task['title']}") def save(self, filename): import json with open(filename, 'w') as f: json.dump(self.tasks, f) def load(self, filename): import json with open(filename, 'r') as f: self.tasks = json.load(f)预期结果
display() shows numbered 任务使用 [x] or [ ] 状态. 保存/加载 persist 到 JSON.
- 4
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
- 5
编写单元测试
使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。
代码import unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()预期结果
运行 python test.py 后输出 OK,三个测试用例全部通过。
自己动手试试
# TODO: define the TodoList class with add, complete, remove, display, save, load
# Then test:
# todo = TodoList()
# todo.add('Learn Python')
# todo.add('Build project')
# todo.complete(0)
# todo.display()
import json
class TodoList:
def __init__(self):
self.tasks = []
def add(self, title):
self.tasks.append({"title": title, "done": False})
print(f"Added: {title}")
def complete(self, index):
if 0 <= index < len(self.tasks):
self.tasks[index]["done"] = True
print(f"Completed: {self.tasks[index]['title']}")
def remove(self, index):
if 0 <= index < len(self.tasks):
removed = self.tasks.pop(index)
print(f"Removed: {removed['title']}")
def display(self):
if not self.tasks:
print("No tasks.")
return
for i, task in enumerate(self.tasks):
status = "[x]" if task["done"] else "[ ]"
print(f"{i}. {status} {task['title']}")
def save(self, filename):
with open(filename, 'w') as f:
json.dump(self.tasks, f)
def load(self, filename):
with open(filename, 'r') as f:
self.tasks = json.load(f)
todo = TodoList()
todo.add('Learn Python')
todo.add('Build project')
todo.complete(0)
todo.display()你学到了什么
你构建 OOP 任务 manager 使用状态, 方法, 边界检查, and JSON persistence — 架构后面许多真实-世界 CLI tools and applications.
相关资源
相关课程
- 类 and 对象
OOP 基本.
- JSON Handling
Serialization.
相关练习
- self 参数测验
练习 OOP.
- Predict 类输出
Predict 类 behavior.
相关速查表
- Python Cheatsheet
类 and JSON 引用.
相关术语
- Dictionary
任务 storage.
- 列表
任务列表.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
- Dictionary
任务 storage.
- 列表
任务列表.
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。