python 生成器和函數之間的區別

def fun():
    print('this is a function!')
    '''
    #secction 1
    #no while loop, run follow code and exit!
    n = 0
    yield n
    n = n+1
    print('over!')
    '''
    #section 2
    n = 0
    while True:
        yield n
        n = n+1
        if n == 5:
            print('over! and exit!')
            return

f = fun() # not execute the func() fucntion
print('call the fun')
for i in f:
    print('i = %s'%i)

 

有以下幾點需要明確:

1. 生成器和函數是不相同的,對於函數的話,f  = fun(),就會立即執行fun()中的代碼段,但是從上圖的結果來看,生成器卻沒有執行,說明f只是一個fun()生成器的一個副本,並沒有進行實際的賦值運算

2. 在用next()進行迭代的時候,在生成器fun()中如果執行完畢就會退出

在section 1代碼段中,如果沒有while循環,就直接執行第二次的時候,就直接退出了

在section 2代碼段中,有while循環,就會不斷的在while循環中進行迭代,循環執行,直至滿足退出條件!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章