How to concatenate Object with a string (primitive) without overloading and explicit type cast (str())?
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
Output:
Traceback (most recent call last):
File "test.py", line 10, in <module>
_string = Foo('text') + 'string'
TypeError: unsupported operand type(s) for +: 'type' and 'str'
operator + must be overloaded?
Is there other ways (just wondering)?
PS: I know about overloading operators and type casting (like str(Foo('text')))
strto force the object into a string?str, you create a new string object by the return value ofMyType.__str__. Casting is taking the same data in memory and telling the compiler/interpreter that it is another object type.__ str__doesn't return the string?__str__does return the string. But it isn't called when+is used, because python doesn't know what+means in this case. You have to tell it explicitly.