0

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.

2 Answers 2

4

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 ;-)

Sign up to request clarification or add additional context in comments.

2 Comments

oops. I was typing that out by hand and just forgot them. The real code is correct.
Note that the default implementation of __str__() simply calls __repr__(), so if you want both to do the same, you only need to define __repr__().
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.