Generator and iterator in python, python generator Generator

Source: Internet
Author: User
Tags generator generator

Generator and iterator in python, python generator Generator

I personally think that iterator and yield implement the same functions, but iterator must be implemented in the class, and yield is implemented in the real function, both of which will save the status.

The generator is also implemented by the iterator.

#! /Usr/bin/env python # coding: UTF-8 # defines three functions: def Lee (name, age): return 'I am % s, I am % d old '% (name, age) def Marlon (): return' I am Marlon 'def Allen (): return' I am Allen 'function_list = [Lee, marlon, Allen] # list of three functions # define a generator def MyGenerator (* args): for I in args: yield I a = MyGenerator (* function_list) # generator print apply (. next (), ('lil', 29) # execute the next () method. The current execution status is saved. When the next () method is called, print apply (. next ()) Print apply (a. next () # Why does yield have the next method? Looking at the column child of the iterator below, we will understand why the generator is implemented by the iterator # Below is an example of the iterator. If a class implements the _ iter _ method, the next () method is called the iterator class MyIterator (object): def _ init _ (self, funcs): self. total_funcs = len (funcs) # record the total number of functions to be executed self. func_list = funcs # record all functions self. step = 0 # record which function def _ iter _ (self): pass def next (self): if self. step <self. total_funcs: # self. step + = 1 # step return self. func_list [self. step-1] # Run the current function else: raise StopIteration c = MyIterator (function_list) print apply (c. next (), ('Lee ', 29) print apply (c. next () print apply (c. next ())


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.