MWB
MWB

Reputation: 12567

How to make print use my class's __str__?

Is there any way to make Python's print use my class's __str__, when they are contained by other classes?

class C(object):
    def __str__(self):
        return 'MyC'

print C() # OK

print [C()] # prints [<__main__.C object at 0x7fb8774e59d0>]

Upvotes: 0

Views: 61

Answers (2)

Keith
Keith

Reputation: 43024

Python will print the reprresentation when in a container, as you see. You can define the __repr__ instead of __str__. However, that one is intended to produce strings that can be evaluated to get the object back again, if possible. So, to handle both of these situations in your case you can do this.

class C(object):
    def __repr__(self):
        return 'C()'

print( C() )

print( [C()] )

Upvotes: 1

Taku
Taku

Reputation: 33714

You have to define __repr__ too since you're not directly calling it's __str__ method and that printing lists calls the values' __repr__ method not __str__.

class C(object):
    def __str__(self):
        return 'MyC'
    def __repr__(self):
        return self.__str__() # return the same result as the __str__ method

print C() # prints MyC

print [C()] # also prints MyC

Upvotes: 3

Related Questions