给出以下代码
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)
我想知道为什么__repr__
在将“ A”添加self.b
到字符串时不调用B。
串联不会导致self.b
被评估为字符串。您需要明确地告诉Python将其强制转换为字符串。
您可以这样做:
return "<A with " + repr(self.b) + " inside>"
但是使用str.format
会更好。
return "<A with {} inside>".format(self.b)
但是,正如jonrsharpe所指出的那样,它将__str__
首先尝试调用(如果存在),以便使其专门使用__repr__
以下语法:{!r}
。
return "<A with {!r} inside>".format(self.b)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句