理解閉包

昨天學到python的切片,有些地方不太理解,只能通過定義上去理解

1 def one():
2     def two():
3         print("hello")
4     return two

如上就是一個普通的閉包

接著來一個帶參數的閉包

1 def one(i):
2     print("i am "+i)
3     def two(j):
4         print("hello"+j)
5     return two

調用one(‘超小咪’)

輸出 i am 超小咪

這裡還返回了一個two函數的引用,所以可以來一個賦值操作

f = one(‘超小咪’)

f(‘tom’)

輸出 i am 超小咪

hello tom

來一個迷惑人的

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

我們再調用fs里的每個函數

fs[0](),fs[1](),fs[2]()

可能以為會輸出1,4,9

其實輸出的是9,9,9