Python实现Todoist任务电子墨水屏显示时遇'Task'对象不可下标错误
解决Todoist新API下'Task' object is not subscriptable错误
我在改造适配电子墨水屏的Todoist任务显示Python代码,原代码依赖的API已废弃,调整API调用后出现唯一问题:执行item = str(my_task['content'])时触发TypeError: 'Task' object is not subscriptable错误。能正常打印整个Task对象,但访问具体属性就会复现该错误。
调用API的代码
def query_todo_list(): global todo_response global do_screen_update print('-= Ping ToDo API =-') while True: try: new_todo_response = Todo.get_tasks() break except ValueError: print('-= ToDo API JSON Failed - Will Try Again =-') time.sleep(todo_wait) except: print('-= ToDo API Too Many Pings - Will Try Again =-') time.sleep(refresh_time) if ((new_todo_response) != (todo_response)): print('-= Task List Change Detected =-') do_screen_update = 1 todo_response = new_todo_response return True
报错代码片段
line_location = 20 for my_task in todo_response: item = str(my_task['content']) priority = str(my_task['priority'])
解决方案
- 新的Todoist API返回的不是字典,而是Task类的实例对象,不能用字典下标(
['key'])的方式访问属性,必须改用**点语法(.)**访问对象属性。 - 修改后的代码:
line_location = 20 for my_task in todo_response: item = str(my_task.content) priority = str(my_task.priority) - 如果不确定Task对象有哪些可用属性,可以先执行
print(dir(my_task))列出所有属性名称,或者用print(my_task.__dict__)查看属性和对应的值。
内容的提问来源于stack exchange,提问作者pslaugh
相关产品推荐
相关产品推荐

