HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to print instances of a class using print()?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howinstancesclassusingprint

Problem

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


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 `` or similar). (In fact, the technique is essentially the same, but trickier to apply.)

Solution

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test


The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() 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.

Code Snippets

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

Context

Stack Overflow Q#1535327, score: 968

Revisions (0)

No revisions yet.