1. 程式人生 > >廖雪峰python3複習總結——day6-2

廖雪峰python3複習總結——day6-2

1、返回函式:函式的返回值為一個函式,這樣函式只有在呼叫時才執行;

def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count()

輸出為
>>> f1()
9
>>> f2()
9
>>> f3()
9

這裡實際上,count()呼叫後返回[f1,f2,f3], 呼叫函式之後, 變數i指向為3.

def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i)) # f(i)立刻被執行,因此i的當前值被傳入f()
    return fs


>>> f1, f2, f3 = count()
>>> f1()
1
>>> f2()
4
>>> f3()
9

與上文的主要區別在於f(i)在函式中已經呼叫了,所以就直接在函式中執行了。實際上count()函式輸出的是一個函式型別的陣列。

練習:

參照網友寫的答案:
雖然思路我也有,但是不知道怎麼表達==、

def createCounter():
    global i
    i=0
    def counter():
        global i
        i+=1
        return i
    return counter

# 測試:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('測試通過!')
else:
    print('測試失敗!')