给出以下代码
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__repr__
“添加”A 时不会调用self.b
到一个字符串。
- https://docs.python.org/3/reference/datamodel.html#object。repr https://docs.python.org/3/reference/datamodel.html#object.__repr__
- https://docs.python.org/3/reference/lexical_analysis.html#operators https://docs.python.org/3/reference/lexical_analysis.html#operators
连接不会导致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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)