Any Number of Items Iterator : method « Class « Python Tutorial






#!/usr/bin/env python

class AnyIter(object):
    def __init__(self, data, safe=False):
        self.safe = safe
        self.iter = iter(data)

    def __iter__(self):
        return self

    def next(self, howmany=1):
        retval = []
        for eachItem  in range(howmany):
            try:
               retval.append(self.iter.next())
            except StopIteration:
               if self.safe:
                    break
               else:
                    raise
        return retval

a = AnyIter(range(10))
i = iter(a)
for j  in range(1,5):
    print j, ':', i.next(j)

i = iter(a)








11.4.method
11.4.1.Methods in class
11.4.2.Intermediate Customization
11.4.3.Any Number of Items Iterator
11.4.4.__str__, __add__, __mul__,__nonzero__,__norm_cval,__cmp__
11.4.5.Wrapping Standard Types
11.4.6.The property() built-in function can take up to four arguments.
11.4.7.A setter
11.4.8.stick in a documentation string for your attribute
11.4.9.Here is our modified class inspired by the recipe:
11.4.10.Class Time with accessor methods.
11.4.11.Methods calling
11.4.12.Add method to a class from outside