Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operator overloading for join

I have a class which instances shall be presented as string if being used in the context of a string. To be precise, a attribute pointing to a string should be returned.

The class looks as the following and works so far:

class Test:
    string = ""

    def __init__(self, value=""):
        self.string = value

    def __repr__(self):
        return str(self.string)

    def __str__(self):
        return self.__repr__()

    def __add__(self, other):
        return "%s%s" % (self.string, other)

    def __radd__(self, other):
        return "%s%s" % (other, self.string)

Unfortunately, I get a TypeError when I try doing something like this:

>>> "-".join([Test("test"), Test("test2")])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found

Doing the same with a string, I get the expected result:

>>> "-".join(["test", "test"])
'test-test'
>>> 

I'm pretty sure I'm just missing the correct operator overload function. Could somebody how to achieve this with class instances in the list?

Thanks.

like image 780
Alex Avatar asked Jun 21 '26 04:06

Alex


1 Answers

join requires elements to be strings, as documented here: https://docs.python.org/3/library/stdtypes.html#str.join

You need to explicitly convert your objects to strings, e.g.:

"-".join(map(str, [Test("test"), Test("test2")]))
like image 85
rburny Avatar answered Jun 22 '26 16:06

rburny