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

时间:2015-08-20 14:34:32

标签: python string class types

给出以下代码

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到字符串。

2 个答案:

答案 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))

它的作品对我来说