Python函数调用中如何省略未使用的参数?
解决方法
给appendJson函数的参数设置默认值,就能实现调用时只传入其中一个参数而不报错,具体修改如下:
首先调整appendJson的函数定义,为task和description指定默认值None:
import json def setTitle(): # 示例:收集用户输入标题 userInput = input("请输入任务标题:") appendJson(task=userInput) def setDescription(): # 示例:收集用户输入描述 userInput = input("请输入任务描述:") appendJson(description=userInput) def appendJson(task=None, description=None): # 读取现有JSON存储文件,文件不存在则初始化空列表 try: with open('tasks.json', 'r', encoding='utf-8') as f: tasks = json.load(f) except FileNotFoundError: tasks = [] # 构建任务条目,仅填充有传入值的字段 task_item = {} if task is not None: task_item['task'] = task if description is not None: task_item['description'] = description # 将新条目写入JSON文件 tasks.append(task_item) with open('tasks.json', 'w', encoding='utf-8') as f: json.dump(tasks, f, indent=4, ensure_ascii=False)
补充说明
- 参数设置默认值后,Python会允许函数调用时省略未传的参数,不会再抛出缺少参数的异常。
- 如果你的需求是更新同一个任务的不同字段(而非添加新任务条目),可以额外增加一个任务ID参数来定位目标任务,示例如下:
def appendJson(task_id, task=None, description=None): # 根据task_id找到对应任务,更新指定字段 try: with open('tasks.json', 'r', encoding='utf-8') as f: tasks = json.load(f) for item in tasks: if item.get('id') == task_id: if task is not None: item['task'] = task if description is not None: item['description'] = description break with open('tasks.json', 'w', encoding='utf-8') as f: json.dump(tasks, f, indent=4, ensure_ascii=False) except FileNotFoundError: print("任务文件不存在")
内容的提问来源于stack exchange,提问作者Mattia Raffaele
相关产品推荐
相关产品推荐

