8.python Object-oriented (implementation of an iterator protocol via __iter__,__next__) with Fibonacci sequence implementations

Source: Internet
Author: User

In front of the iterator and generator principle, it has been said that the __iter__ method and the role of the __next__ method, here do not repeat the description.

In this complement an example of implementing an iterator protocol.

Example 1: (The iterator generates an infinite value before the exception is thrown stopiteration)

Class C1:

def __init__ (Self,start):

Self.start = Start

def __iter__ (self):

return self

Def next (self):

Self.start + = 1

Return Self.start

O1 = C1 (10)

For I in O1:

Print I


Example 2: (After throwing an stopiteration exception)

Class C1:

def __init__ (self,start,stop):

Self.start = Start

Self.stop = Stop

def __iter__ (self):

return self

Def next (self):

If Self.start >= self.stop:

Raise Stopiteration

n = Self.start

Self.start + = 1

return n

O1 = C1 (1,10)

For I in O1:

Print I

Output:

1

2

3

4

5

6

7

8

9


Fibonacci Sequence:

Class Fib:

def __init__ (self):

Self._a=0

Self._b=1

def __iter__ (self):

return self

def __next__ (self):

Self._a,self._b=self._b,self._a + self._b

Return self._a

F1=FIB ()


This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1918569

8.python Object-oriented (implementation of an iterator protocol via __iter__,__next__) with Fibonacci sequence implementations

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.