`

python 之 迭代器

阅读更多

python3.0以前用next() 替换__next__

 

#!/ur/bin/env python

import sys;
import os;

class CFib:
    '''create a fib iterator'''
    
    def __init__(self, nMaxVal):
        self.m_nMaxVal = nMaxVal;
        
    def __iter__(self):
        print("CFib::__iter__");
        
        self.m_nStart = 0;
        self.m_nEnd = 1;
        
        return self;
    
    def __next__(self):
        print("CFib::next");
        
        nFib = self.m_nStart;
        
        if nFib > self.m_nMaxVal:
            raise StopIteration;
        
        self.m_nStart, self.m_nEnd = self.m_nEnd, self.m_nStart + self.m_nEnd;
        return nFib;
#end of class CFib

if "__main__" == __name__:
    fib = CFib(1000);
    
    print(fib);
    print(fib.__doc__);
    
    for i in fib:
         print(i);

    for i in fib:
        print(i);

    
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics