Why can't I use join to list objects that implement __str__?

I am learning a Python duck, I know that if you implement some special methods for a class, you can happily use the built-in methods of the class

eg:

class A:
    def __init__(self,l):
        self._l = l
    def __iter__(self):
        return iter(self._l)

If I do this, I can use for...in..,zipsome other methods that are built-in, and also can do some other things, such as implementation __setitem__(), so I can use random.choice, random.shuffle and I feel that python is so cool, but then I find this problem, I want to use join to print some objects that I implemented with their methods __str__, but this will not work

I find that this is due to the fact that when we use join, we write it like ';'.join(l)so the duck utilities trick will not work for him because he uses str methods and not the objects will be connected

But why? Since many of them are building methods for friendly duck printing, why not “join in”?

@SethMMorton - these are my doubts, thanks I know that I can use ';'.join([str(i) for i in l])to solve my problem, but I do not know why python does not do it myself?

+4
source share
2 answers

"": Python str, __str__ repr , str. Python , , , ( Python ), . __str__ , , , "".

for, zip .. , - ; , .

, , . Python 3. str, :

iterable_of_bytes_objects = b'123', b'456'

','.join(iterable_of_bytes_objects)

"b'123',b'456'", , b :

b','.join(iterable_of_bytes_objects)

, , , decode bytes. , , repr str - . Python , Zen of Python (import this):

.

:

, .

, " ". , ','.join(map(str, iterable)), , , , , Zen:

.

.

+5

. , . , range(). :

';'.join(str(i) for i in l)

string.join(iterable): " , ."

+1

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


All Articles