[Small knowledge] Python iterator-related @ python

Source: Internet
Author: User

classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B    def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself    defNext (self): SELF.A, self.b= self.b, SELF.A + self.b#Calculate Next Value        ifSELF.A > 100000:#conditions for exiting a loop            Raisestopiteration (); returnSelf.a#returns the next value

Implement an iterator that must contain both the __iter__ and next methods. There are two ways to use this class.

One, as a for loop to use:

 for inch Fib (): ...      Print n . ... 11235 ... 4636875025

Second, call the next method.

f = Fib () for in range    :print f.next ()

Printing results:

11235813213455

One more example:

classA (object):def __init__(Self, O): Self.__obj__=odef __getattr__(self, name):ifHasattr (self.__obj__, name):returnGetAttr (self.__obj__, name)returnSelf.__dict__[Name]def __iter__(self):returnSelf.__obj__.__iter__() L=[]a=A (L) forIinchXrange (101): A.append (i)PrintSUM (a)

[Small knowledge] Python iterator-related @ python

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.