python生成器

def func_list_empty(l = []):
    l.append(2)
    return l

def func_list_none(l = None):
    if l == None:
        l = []
    l.append(2)
    return l
        
def test_list_empty(l = []):
    func_list_empty()
    print func_list_empty()
    
    func_list_none()
    print func_list_none()

""" Iter, next """
class xrange_my(object): 
    def __init__(self, max): 
        self.max = max 
        self.b = 0 

    def __iter__(self): 
        return self 

    def next(self): 
        if self.b < self.max: 
            r = self.b 
            self.b = self.b + 1
            return r 
        raise StopIteration()
        
""" Use yield, generator"""        
def xrange_my_yield(max): 
    b = 0
    while b < max: 
        yield b 
        b = b + 1 
                 
def test_yield():
    for l in range(10):
        print "%d," % l
        
    print "======I'm a sperator======"        
    for l in xrange(10):
        print "%d," % l
        
    print "======I'm a sperator======"        
    for l in xrange_my(10):
        print "%d," % l        
        
    print "======I'm a sperator======"        
    for l in xrange_my_yield(10):
        print "%d," % l                

def main():
    test_list_empty()
    test_yield()
    
if __name__ == "__main__"    :
    main()

 

posted on 2016-08-03 15:59  与非朋仔  阅读(159)  评论(0编辑  收藏  举报

导航