[Python] Shallow Explorer Generator

Is a class

Classes that contain both u iter_u() and u next_() methods are generators.

Getting Method

There are several common
eg.1 generator

lst = [1,2,3,4]
generator = (x for x in lst)

Note that parentheses are not'[]', otherwise the generation will be an array.
Compared to the array generated with'[]', only the generator is generated here, and the data is generated when it is needed, which has a significant memory consumption advantage when there is a large amount of data.

eg.2 generator method generator function

lst = [1,2,3,4]
def GetGenerator():
    for t in lst:
        yield t
generator = GetGenerator()

Any method that contains a field is a generator function, and the return value from the method call is a generator.

Usage method

The idea of the generator is to get the data on demand so that you don't have to generate it all at once.The generated data can be obtained by next(generator) or generator. u next_(), it is important to note that if the amount of data obtained exceeds the amount of data owned by the generator, a StopIteration exception will be thrown.

Three basic application examples

# generator
class Example(object):
    def __init__(self):
        self.m_lst = [
            (1, 'Zhang San'),
            (2, 'Li Si'),
            (3, 'King Five'),
            (4, 'Zhao Six'),

    def Apply_GetTupleGenerator(self):
        for t in self.m_lst:
            yield t

    def Apply_Traversing(self):
        generator = (t for t in self.m_lst)
        for t in generator:

    def Apply_Enum(self, nBegin = 0):
        def _enum():
            nIdx = nBegin
                yield nIdx
                nIdx += 1
        return _enum().__next__

if __name__ == "__main__":
    example = Example()
    # Application 1: Basic use of generator
    generator = example.Apply_GetTupleGenerator()
    print(next(generator)) # (1,'Zhang San')
    print(next(generator)) # (2,'Li Si')
    print(next(generator)) # (3,'Wang Wu')
    print(next(generator)) # (4,'Zhao Six')
    # Application 2: Traversal
    example.Apply_Traversing() # Output the same four sentences as above
    # Application 3: Enumeration
    enum = example.Apply_Enum()
    print(enum()) # 0
    print(enum()) # 1
    print(enum()) # 2
    print(enum()) # 3

Added by Bozebo on Wed, 19 Feb 2020 18:47:18 +0200