给出以下代码
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)
我想知道为什么B&#39; __repr__
在&#34;添加&#34; A&#39; self.b
到字符串。
答案 0 :(得分:6)
连接不会导致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)
答案 1 :(得分:-2)
您可以使用repr()
class A:
def __init__(self):
self.b = repr(B())
def __repr__(self):
return "<A with " + self.b + " inside>"
class B:
def __repr__(self):
return "<B>"
a = A()
print(repr(a))
它的作品对我来说