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'))
)
Just define the __add__()
and __radd__()
methods:
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
def __add__(self, other):
return str(self) + other
def __radd__(self, other):
return other + str(self)
They will be called depending on whether you do Foo("b") + "a"
(calls __add__()
) or "a" + Foo("b")
(calls __radd__()
).
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