Generators and iterators in Python

Source: Internet
Author: User

Personally feel that iterator and yield achieve the same function, but iterator need to implement in the class, yield is implemented in the real function, both will save the state

The generator is also implemented by iterators

#!/usr/bin/env python#coding:utf-8# definition three functions def Lee (name,age): Return ' I am%s,i am%d old '% (name,age) def Ma Rlon (): Return ' I am Marlon ' Def Allen (): Return ' I am Allen ' function_list= [Lee,marlon,allen] #有三个函数的列表 # definition A generator def mygenerator (*args): For i in Args:yield I a=mygenerator (*function_list) #生成器print apply (A.next (' Lee ',)) #执行next () method, which saves the current execution state, and the next time the next () method is called, print apply (A.next ()) print apply (A.next ()) # Why does yield have next method? Look at the iterator below to see why the generator is implemented by the iterator # below is an example of an iterator, a class that implements the __iter__ method, and the next () method, which is called an iterator class Myiterator (object): Def __init__ (Self,funcs): Self.total_funcs=len (funcs) #记录总共需要执行多少个函数 self.func_list=funcs #记录所有函数 self.step = 0 #记 Record which function is currently executed Def __iter__ (self): Pass def Next: If Self.step < self.total_funcs: #当目前所            The function being executed is less than the total number of functions Self.step+=1 #step return self.func_list[self.step-1] #执行当前函数 else: Raise Stopiteration       C=myiterator (function_list) print apply (C.next (), (' Lee ', +)) print apply (C.next ()) print apply (C.next ()) 


Generators and iterators in Python

Related Article

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.