Bulba! wrote:
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]

Here's one way: # (Make __iter__ an iterator)

Py> class R1(object):
        def __init__(self, data):
            self.data = data
            self.i = len(data)
        def __iter__(self):
            while self.i > 0:
                self.i -= 1
                yield self.data[self.i]

Py> s=R1('spam')
Py> list(s)
['m', 'a', 'p', 's']
Py> list(s)
[]
Py> s.i = 3
Py> list(s)
['a', 'p', 's']

Here's another way: # (Return something with __iter__ and next methods)

Py> class R2(object):
        def __init__(self, data):
            self.d = data
            self.i = len(data)
        def __iter__(self):
            return iter(self.d)
Py> s = R2('spam')
Py> list(s)
['s', 'p', 'a', 'm']
Py> list(s)
['s', 'p', 'a', 'm']

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to