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?

2
  • you could override __repr__ too Commented May 16, 2013 at 19:14
  • @Joran Beasley and unutbu, both of you gave useful answers. Joran, I decided to accept your answer since you answered first. Commented May 16, 2013 at 19:35

2 Answers 2

5

you would need to define its __repr__ method I believe

class CustomClass:
     def __str__: 
         return "whatever"
     def __repr__:
         return str(self)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I don't know why I didn't think to try that.
When you implement str sometimes you may also want to implement unicode too - for differences check stackoverflow.com/questions/1307014/…
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.