lovefaithswing
lovefaithswing

Reputation: 1540

Python instance string in a list

I have a simple class in python that has a __str__() function. Like this:

class Foo(object):
   def __init__():
       self.name = 'something'

   def __str__():
       return self.name

My real class does more than that, but this is an example.

So then I do this:

a = Foo()
b = Foo()

print a
print b
print [a,b]

Except this prints:

something
something
[<Foo object at HexString>,<Foo object at HexString>]

Why is the printed version in the list not printing the str name of the instance and is there an easy way to get it to?

I've tried to see if __unicode__ is different and it is not.

Upvotes: 0

Views: 501

Answers (2)

Cameron
Cameron

Reputation: 98816

You need to add a __repr__ method as well:

class Foo(object):
   def __repr__(self):
       return str(self)

   def __str__(self):
       return self.name

See this question about the difference between __str__ and __repr__.

Note also that you're missing the self arguments to the methods in your sample code ;-)

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 602105

The string representation of the list actually calls __repr__() on every item -- so just overwrite that method.

Upvotes: 3

Related Questions