Iteratable object, iterator (object), generator (object)

Keywords: Python

iterator

Iteratable object: an iteratable object implements the iterator method, which returns an iterator object.

Iterator: so what iterator? It is a stateful object, which can return the next value in the container when you call the next() method. Any object that implements the uiter UPU and unext UPU (implementing the next() method in python2) methods is an iterator, and uiter UPU returns the iterator itself, and unext UPU returns the next value in the container. If there are no more elements in the container, a StopIteration exception is thrown.

a = ['aaa', 'bbb', 'ccc']
my_iterable = MyIterable(a)
res2 = iter(my_iterable)

while True:
    try:
        print(next(res2))
    except StopIteration as e:
        break

generator

class Project(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def isPrimeNum(self, k): #  Judgement prime number
        if k < 2:
            return False
        for i in range(2, k):
            if k % i == 0:
                return False
        return True

    def __iter__(self):
        for i in range(self.start, self.end):
            if self.isPrimeNum(i):
                yield i

###################################
res = Project(1,100)
print(iter(res))

The custom generator of positive and negative order

class MyFloatRange(object):
    def __init__(self, start, end, step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        for i in range(self.start, self.end):
            if self.start <= self.end:
                yield self.start
                self.start += self.step

    def __reversed__(self):
        for i in range(self.start, self.end):
            if self.start <= self.end:
                yield self.end
                self.end -= self.step


for i in MyFloatRange(1, 11, 2):
    print(i)

for i in reversed(MyFloatRange(1, 11, 2)):
    print(i)

Light purple text

Posted by JStefan on Sun, 03 May 2020 00:12:45 -0700