for source code implementation

for source code implementation

We know that, and for the java while basically achieve the same function, it will not have any shortcomings, while java iterator is particularly troublesome.

python for a while and is different in the case of implementing iterative capability, but also for each iteration of data out of the processing.

for the three object can iterate

1. By default there __iter__()are objects, that is, iterables

class zx:
    def __init__(self):
        self.ls = [1,2,3,4]
    def __iter__(self):
        for i in self.ls:
            yield i
z=zx()
for i in z:
    print(i)

2. By default there __iter__()和__next__(), that is iterator object

class zx:
    def __init__(self):
        self.ls = [1,2,3,4]
        self.i = -1
    def __iter__(self):
        return self
    def __next__(self):
        if self.i < self.ls.__len__()-1:
            self.i+=1
            return self.ls[self.i]
        else:
            raise StopIteration
z=zx()
for i in z:
    print(i)

3. By default there__getitems__()

class zx:
    def __init__(self):
        self.ls = [1,2,3,4]
    def __getitem__(self, item):
        return self.ls[item]
z=zx()
for i in z:
    print(i)

doubt

1. I do not know if you have such a question, why iterator object and iteration object has a __iter__()method, which in fact and for the fulfillment of the relevant

2. We know we manually __next__()when there is no data iteration, it will report a StopIteration, used for why will not appear, in fact, has helped us for capturing and processing the exception

to sum up

1) for .... in iterable, first call iter (iterable) function returns an iterator iterator

2) per cycle, called once the object __next__(self)until the last value, called again will trigger StopIteration

3) for circulating captured StopIteration, thereby ending the cycle

1 to note that iterables call __iter__()is equivalent to creating a new iterator object, from the very beginning of iterations, while calling iterator object __iter__()returned is itself, before the iteration to which position, or continue to the next iteration where

Guess you like

Origin www.cnblogs.com/zx125/p/11614062.html