1. 程式人生 > >python Class: 面向對象高級編程 __iter__ 和 next()

python Class: 面向對象高級編程 __iter__ 和 next()

turn std png nag fib cto 1.2 cts resp

官網解釋:

New in version 2.2.

  • iterator.__iter__()

  • Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and instatements. 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 are 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.


也就是說 __iter__與next()是配套使用的。


Fibonacci數列:

#!/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


運行失敗:

技術分享圖片


怎麽用class做才能成功呢?????

後來,才發現,我2.7版本的解釋器不支持,用網頁上的Python3在線編程解釋器完美運行。。。。。。is ri le gou le.

附使用的python3環境:http://www.dooccn.com/python3/


請問各位大佬,在2.7版本中我該怎麽使用 __iter__ 呢??求教!!!


python Class: 面向對象高級編程 __iter__ 和 next()