Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing class instance
#1
I have a class with todo's (text and id) and import that class in my main program where I want to print it.

classtodo.py:
class ToDo:
    def __init__(self, todo_id, todo_text):
        self.todo_id = todo_id
        self.todo_text = todo_text

    def __str__(self):
        return "{}:{}".format(self.todo_id, self.todo_text)
main.py:
import classtodo
todos =[]
#Funktion ToDos Anlegen
def todos_new():
    todo_id = 1
    todo_text = "text1"
    new = classtodo.ToDo(todo_id, todo_text)
    todos.append(new)

def todos_print():
    print(str(todos))

todos_new()
todos_print()
The output I get is
Output:
[<classtodo.ToDo object at 0x1040611d0>]
- any idea what I'm doing wrong? I actually want to get the id (1) and the text (text1). I use Python 3.7. Thanks!
Reply
#2
When you print a list, python prints the repr() of the list items instead of their str(). You can do this
print([str(x) for x in todos])
Reply
#3
Okay. Thanks a lot!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Printing out incidence values for Class Object SquderDragon 3 258 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  Access instance of a class Pavel_47 5 2,066 Nov-19-2021, 10:05 AM
Last Post: Gribouillis
  Class Instance angus1964 4 2,437 Jun-22-2021, 08:50 AM
Last Post: angus1964
  Can we access instance variable of parent class in child class using inheritance akdube 3 13,954 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Issue referencing new instance from other class nanok66 3 2,208 Jul-31-2020, 02:07 AM
Last Post: nanok66
  Class variable / instance variable ifigazsi 9 4,289 Jul-28-2020, 11:40 AM
Last Post: buran
  printing class properties from numpy.ndarrays of objects pjfarley3 2 1,939 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  Python complains that class instance is not defined colt 3 5,625 Sep-17-2019, 12:32 AM
Last Post: ichabod801
  how to add class instance attributes from list 999masks 2 2,696 Jul-22-2019, 07:59 AM
Last Post: 999masks
  Trying to set an instance variable to current value of a class variable ScottDiesing 3 2,761 Feb-15-2019, 03:12 PM
Last Post: ScottDiesing

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020