Given the following code
class A:
def __init__(self ):
self.b = B()
def __repr__(self):
#return "<A with {} inside>".format( self.b )
#return "<A with " + repr(self.b) + " inside>"
return "<A with " + self.b + " inside>" # TypeError: Can't convert 'B' object to str implicitly
class B:
def __repr__(self):
return "<B>"
a = A()
print(a)
I am wondering why B's __repr__
is not called when "adding" A's self.b
to a string.
Concatenation doesn't cause
self.b
to be evaluated as a string. You need to explicitly tell Python to coerce it into a string.You could do:
But using
str.format
would be better.However as jonrsharpe points out that would try to call
__str__
first (if it exists), in order to make it specifically use__repr__
there's this syntax:{!r}
.You can use repr()
its works for me