Python: Implicit conversion of object to str?

2019-06-17 02:26发布

Given the following code

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)

I am wondering why B's __repr__ is not called when "adding" A's self.b to a string.

2条回答
欢心
2楼-- · 2019-06-17 02:57

Concatenation doesn't cause self.b to be evaluated as a string. You need to explicitly tell Python to coerce it into a string.

You could do:

return "<A with " + repr(self.b)  + " inside>"

But using str.format would be better.

return "<A with {} inside>".format(self.b)

However as jonrsharpe points out that would try to call __str__ first (if it exists), in order to make it specifically use __repr__ there's this syntax: {!r}.

return "<A with {!r} inside>".format(self.b)
查看更多
祖国的老花朵
3楼-- · 2019-06-17 03:07

You can use 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))

its works for me

查看更多
登录 后发表回答