0

I have a simple class I created:

class C:
    def __init__(self):
        self.a = 1

and I want to print a list of objects from this class using a function I created:

def p(s):
    print('hi ', s)

This is how I want to call the printing function p: p([C() for i in range(3)])

Unfortunately, this produces hi [<__main__.C object at 0x000000F92A8B9080>, <__main__.C object at 0x000000F92AB0E898>, <__main__.C object at 0x000000F92AB0E978>].

I thought the problem was due to not implementing __str__ so I changed my class into:

class C:
def __init__(self):
    self.a = 1
def __str__(self):
    return str(self.a)

but I get the same result :(

What I hoped for was hi [1, 1, 1] or hi 1, 1, 1 or something like that, not the memory location of the objects I created.

I can use

for i in range(3): p(C())

but I want to pass a list of objects to the p function rather than call it for each of my objects. Is that possible?

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

1 Answers1

1

Replace __str__ with __repr__:

def __repr__(self):
    return str(self.a)
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79