-2

I'm trying to iterate over User objects stored in a python list called myusers then print each. This is what I've done:

class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age

myusers= [User("Fred", "30"), User("Doe", "20")] 

for i in range(2):
    print(str(myusers[i]))

what I get from the above is the memory location as follows:

<__main__.User object at 0x000001FD807B4250>
<__main__.User object at 0x000001FD807F13A0>

However, I was expecting to get:

User("Fred", "30")
User("Doe", "20")

I've seen this question: https://stackoverflow.com/questions/59115308/print-out-objects-stored-in-a-list but it didn't answer my question since I'm using str in the print function. Can anyone let me know when I'm not getting this value?

Simon
  • 113
  • 1
  • 8

1 Answers1

1

As remarked in the comments, you should define a __str__ method, which defines how to represent your object as a string.

class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return f'User("{self.name}", "{self.age}")'

myusers= [User("Fred", "30"), User("Doe", "20")] 

for i in range(2):
    print(myusers[i])