Like str.join () in a list of objects

class A:
    def __init__(self, text):
        self.text = text

    def __repr__(self):
        return self.text

    def __str__(self):
        return self.text

    def __add__(self, other):
        return str(self) + other

    def __radd__(self, other):
        return other + str(self)

I want the list of objects to Abe "compatible" with str.join () . What special method should be implemented to achieve this?

Of course, I can extract the list of text first and then join it, but that is not what I want.

b = A('Hello')
c = A('World')
l = [b, c]

print b, c
print l
print b + ' ' + c
print ' '.join(l) # <- Error here

Hello World
[Hello, World]
Hello World
Traceback (most recent call last):
  File "sandbox.py", line 24, in <module>
    print ' '.join(l)
TypeError: sequence item 0: expected string, instance found
+4
source share
1 answer

__str__used only if the user of your object wants to turn it into a string, but str.joinnot. You must explicitly convert your objects to values strbefore you str.joinuse them.

(Could str.join str , ? , .)

Python: " , ". str.join , str join.

print(' '.join(str(x) for x in l))

join str , str, A str.

class A(str):
    def __new__(cls, text):
        obj = super().__new__(cls, text)
        # Do whatever else you need to add to obj
        return obj

l = [A('hello'), A('world')]
print(' '.join(l))

, .

+11

Source: https://habr.com/ru/post/1687238/


All Articles