When I try to print an instance of a class, I get an output like this:
>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>
How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)?
See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than <class __main__.Test> or similar). (In fact, the technique is essentially the same, but trickier to apply.)
The
__str__method is what gets called happens when you print it, and the__repr__method is what happens when you use therepr()function (or when you look at it with the interactive prompt).If no
__str__method is given, Python will print the result of__repr__instead. If you define__str__but not__repr__, Python will use what you see above as the__repr__, but still use__str__for printing.