Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate `Object` with a string?

Tags:

python

casting

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')))

like image 324
tomas Avatar asked Feb 16 '12 16:02

tomas


1 Answers

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__()).

like image 134
Sven Marnach Avatar answered Oct 05 '22 20:10

Sven Marnach