【问题标题】:Having trouble printing objects with __str__ in Python在 Python 中使用 __str__ 打印对象时遇到问题
【发布时间】: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 实例的列表。

标签: python sql oop


【解决方案1】:

您返回的是 .fetchall() 而不是新的类实例,因此您可以破解它来打印它:

class Task:
    def __init__(self, taskID, description, completed):
        self.taskID = taskID
        self.description = description
        self.completed = completed

    def __str__(self):
        print(self.description + " DONE!")

让其他类喜欢

def readDatabase():
    query = '''SELECT * FROM Task'''
    c.execute(query)
    tasks = c.fetchall()

    for task in tasks:
        tlo.Task(task[0], task[1], task[2])

然后打电话

readDatabase()

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2011-04-03
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多