1

I have a list of objects. I am trying to output a meaningful representation of the objects in the list, that reveals some of the instance variables, using the string formatting capability built into recent versions of Python. I am using Python 3.3.0.

I have defined a __str__ method in the class for the objects in my list. If I try to print an individual object, I get the representation returned by the __str__ method. But if I try to print the whole list, I get the generic representation, as if I haven't defined the __str__ method. Here is an example:

class CustomClass:
    def __init__(self):
        self.instanceVar = 42

    def __str__(self):
        return "{} (instanceVar = {})".format(self.__class__.__name__, self.instanceVar)

testObject = CustomClass()

print("{}".format(testObject))
# CustomClass (instanceVar = 42)

print("{}".format([testObject]))
# [<__main__.CustomClass object at 0x1006cbed0>]

How can I get the 2nd print statement to print something like [CustomClass (instanceVar = 42)]? Is it possible to do this just by passing the right format string to the print function or is it more complicated than that?

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148

2 Answers2

5

you would need to define its __repr__ method I believe

class CustomClass:
     def __str__: 
         return "whatever"
     def __repr__:
         return str(self)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thanks. I don't know why I didn't think to try that. – Elias Zamaria May 16 '13 at 19:16
  • When you implement __str__ sometimes you may also want to implement __unicode__ too - for differences check http://stackoverflow.com/questions/1307014/python-str-versus-unicode#1307210 – Robert Lujo May 16 '13 at 19:36
3

When printing a list, you get the repr of the objects in the list. So to get the desired format, define the __repr__ method.

If you do not define __str__, but define __repr__, then the __repr__ will be used in place of __str__ whenever Python tries to find the str of the object. So you don't have to define both if you don't want to.

class CustomClass:
    def __init__(self):
        self.instanceVar = 42

    def __repr__(self):
        return "{} (instanceVar = {})".format(self.__class__.__name__, self.instanceVar)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677