【发布时间】:2023-03-23 04:03:01
【问题描述】:
我无法让我的对象按照我希望它们使用 __str__ 的方式打印。我希望每个任务对象都打印有“完成!”这个词。如果任务已经完成(即任务对象的索引 2 等于 1),但每次我调用 viewCompleted() 时,程序都会将每个对象作为一个元组返回。
主模块中调用viewCompleted()的if语句:
import Task_List_Database as tld
if user_command.lower() == "history":
tld.viewCompleted()
对象构造函数和__str__
class Task:
def __init__(self, taskID, description, completed):
self.taskID = taskID
self.description = description
self.completed = completed
def __str__(self):
return self.description + " DONE!"
import sqlite3
import Task_List_Objects as tlo
conn = sqlite3.connect("task_list_db.sqlite")
c = conn.cursor()
def readDatabase():
query = '''SELECT * FROM Task'''
c.execute(query)
tasks = c.fetchall()
for task in tasks:
tlo.Task(task[0], task[1], task[2])
return tasks
def viewCompleted():
tasks = readDatabase()
task_count = 1
for task in tasks:
if task[2] == 1:
print(task)
task_count += 1
print()
出现__str__问题的输出:
Command: history
(1, 'Get bike fixed', 1)
(2, 'Call your mom', 1)
(3, 'Buy toothbrush', 1)
(4, 'Do homework', 1)
任何帮助解释为什么 __str__ 没有按我的意图工作将不胜感激!
【问题讨论】:
-
tasks只是c.fetchall的输出,而不是Task实例。 -
你在
readDatabase(),又名元组中返回tasks。我相信您想返回Task实例的列表。