简体   繁体   中英

Having trouble printing objects with __str__ in Python

I am having trouble getting my objects to print the way I want them to using __str__. I want each Task object to be printed with the word "DONE." if the task has been completed (ie, the index 2 for the task object is equal to 1). but each time I call viewCompleted() the program returns each object as a tuple.

The if statement in the main module that calls viewCompleted():

import Task_List_Database as tld

if user_command.lower() == "history":
            tld.viewCompleted()

Object Constructor and __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()

Output where __str__ problem occurs:

Command: history
(1, 'Get bike fixed', 1)
(2, 'Call your mom', 1)
(3, 'Buy toothbrush', 1)
(4, 'Do homework', 1)

Any help explaining why __str__ isn't working the way I intend would be greatly appreciated!

You are returning the .fetchall() not the new class instance, so you can hack it to print it:

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

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

And make the other class like

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

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

And call like

readDatabase()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM