Str in Python 2.7 does not have __iter__, but it acts as iterable. What for?

I was checking str objects in Python, and I realized that the str object in Python 2.7 does not have the __iter__() or next() method, while in python 3.0 objects it has the __iter__() method and therefore they are repeatable. However, I can still use str objects as if they were iterable in Python 2.7. For example, I can use them for loops. How it works?

+6
source share
1 answer

The simple answer is: since iter(s) returns an iterable object.

Longer answer: iter() looks for the __iter__() method, but if it does not find it, it tries to build the iterator itself. Any object that supports __getitem__() with integer indices starting at 0 can be used to create a simple iterator. __getitem__() is a function behind row / row indexing, for example s[0] .

 >>> "abc".__iter__() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute '__iter__' >>> iter("abc") <iterator object at 0x1004ad790> >>> iter("abc").next() 'a' 

See here for more details.

+4
source

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


All Articles