B
Bulba!
Hello Mr Everyone,
From:
http://docs.python.org/tut/node11.html#SECTION0011900000000000000000
"Define a __iter__() method which returns an object with a next()
method. If the class defines next(), then __iter__() can just return
self:"
The thing is, I tried to define __iter__() directly without explicit
defining next (after all, the conclusion from this passage should
be that it's possible).
class R:
def __init__(self, d):
self.d=d
self.i=len(d)
def __iter__(self):
if self.i == 0:
raise StopIteration
self.i -= 1
return self.d[self.i]
['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']
Apparently no, there is no next() method. Let's see
if iterator works:
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 7, in __iter__
StopIteration
OK, this part works. But this:
print i
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: __iter__ returned non-iterator of type 'str'
So which is it? Does next() method HAS to be defined
explicitly? That's what Wikipedia says:
http://en.wikipedia.org/wiki/Iterator#Python
"Any user defined class can support standard iteration (either
implicit or explicit) by defining an __iter__() method which creates
an iterator object. The iterator object then needs to define both an
__iter__() method as well as a next() method."
From:
http://docs.python.org/tut/node11.html#SECTION0011900000000000000000
"Define a __iter__() method which returns an object with a next()
method. If the class defines next(), then __iter__() can just return
self:"
The thing is, I tried to define __iter__() directly without explicit
defining next (after all, the conclusion from this passage should
be that it's possible).
class R:
def __init__(self, d):
self.d=d
self.i=len(d)
def __iter__(self):
if self.i == 0:
raise StopIteration
self.i -= 1
return self.d[self.i]
['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']
Apparently no, there is no next() method. Let's see
if iterator works:
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 7, in __iter__
StopIteration
OK, this part works. But this:
print i
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: __iter__ returned non-iterator of type 'str'
So which is it? Does next() method HAS to be defined
explicitly? That's what Wikipedia says:
http://en.wikipedia.org/wiki/Iterator#Python
"Any user defined class can support standard iteration (either
implicit or explicit) by defining an __iter__() method which creates
an iterator object. The iterator object then needs to define both an
__iter__() method as well as a next() method."