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.
This error message Can't convert 'int' object to str implicitly is clear, when concatenating strings with integers - you can't directly stick together a string and an integer. So, in order to resolve this problem, you have to explicitly parse the integer to a string by the str() built-in function .
Use the str() class to convert an object to a string, e.g. result = str(my_object) . The str() class returns the string version of the given object.
Implicit Type Conversion is automatically performed by the Python interpreter. Python avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.
Implicit data type conversion is done automatically by the python compiler without any involvement of the user. The compiler converts smaller data types into larger data types to prevent any loss of data, for example, conversion of int to float.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With