Python Class: Object-oriented advanced programming __iter__ and Next ()

Source: Internet
Author: User

website Explanation:

New in version 2.2.

  • iterator.__iter__()

  • Return the iterator object itself . This was required to allow both containers and iterators to being used with The for  and in statements. This method corresponds to The tp_iter  slot of the type structure for Python objects in the python/c API.

  • iterator . next (

  • Return the next item from the container. If There is no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the python/c API.


That is to say, __iter__ and next () are used in support.


Fibonacci Series:

#!/usr/bin/python

#-*-Coding:utf-8-*-


Class Fibo (object):

def __init__ (self):

SELF.A, self.b = 0, 1

def __iter__ (self):

return self

def __next__ (self):

SELF.A, self.b = self.b, SELF.A + self.b

If SELF.A > 10000:

Raise Stopiteration ()

Return SELF.A, self.b



For n in Fibo ():

Print n


Failed to run:


How do you use class to succeed?????

Later, only to find that my 2.7 version of the interpreter is not supported, using the PYTHON3 online programming interpreter on the Web is perfect to run ... is Ri le gou le.

Python3 Environment for use: http://www.dooccn.com/python3/


I would like to ask you guys, in the 2.7 version of how should I use __iter__?? Ask for advice!


Python Class: Object-oriented advanced programming __iter__ and next ()

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.