Why when you call the __next__()
method on str
it says it does not have this method ...
b = 'hello'
b.__next__() # give AttributeError: 'str' object has no attribute '__next__'
a = iter(b)
a.__next__() # output == 'h'
Does not the __iter__()
method return self? Well, if it returns self, it is a string that does not have the __next__()
method?
So how does return "h"
?
iter
only returns its argument if the value is an iterator. str
is not an iterator; it is an iterable whose __iter__
method returns a str_iterator
object.
>>> a = iter(b)
>>> type(a)
<class 'str_iterator'>
The str_iterator
object implements __next__
, and maintains iteration state separate from any other iterator over the same object.
>>> b = 'hello'
>>> a1 = iter(b)
>>> a2 = iter(b)
>>> next(a1)
'h'
>>> next(a2)
'h'
>>> next(a2)
'e'
>>> next(a2)
'l'
>>> next(a1)
'e'
You could picture str_iterator
being defined something like
class str_iterator:
def __init__(self, s):
self.s = s
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == len(self.s):
raise StopIteration
i = self.i
self.i += 1
return self.s[i]
class str:
...
def __iter__(s):
return str_iterator(s)
The iterator remembers is position in the string between calls to __next__
. The job of __next__
is to advance the "pointer" and to return the character at the correct position.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments