handle
handle

Reputation: 6299

Python: Implicit conversion of object to str?

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.

Upvotes: 7

Views: 4626

Answers (2)

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

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)

Upvotes: 6

Honnisha
Honnisha

Reputation: 53

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

Upvotes: -2

Related Questions