Python:将对象隐式转换为str?

han*_*dle 7 python string types class

给出以下代码

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)
Run Code Online (Sandbox Code Playgroud)

我想知道为什么__repr__在将"A"添加self.b到字符串时不会调用B.

Sup*_*Man 6

串联不会导致self.b被评估为字符串。您需要明确地告诉Python将其强制转换为字符串。

您可以这样做:

return "<A with " + repr(self.b)  + " inside>"
Run Code Online (Sandbox Code Playgroud)

但是使用str.format会更好。

return "<A with {} inside>".format(self.b)
Run Code Online (Sandbox Code Playgroud)

但是,正如jonrsharpe所指出的那样,它将__str__首先尝试调用(如果存在),以便使其专门使用__repr__以下语法:{!r}

return "<A with {!r} inside>".format(self.b)
Run Code Online (Sandbox Code Playgroud)