Given the following code
class A:
def __init__(self ):
self.b = B()
def __repr__(self):
#return "".format( self.b )
#return ""
return "" # TypeError: Can't convert 'B' object to str implicitly
class B:
def __repr__(self):
return ""
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:
return ""
But using str.format would be better.
return "".format(self.b)
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}.
return "".format(self.b)