5 3 Python 函式物件與閉包

2021-07-23 18:34:36 字數 1524 閱讀 7542

函式在python中也是物件,也就是說函式也可以當成引數傳遞給其他函式,放在資料結構中,也可以作為函式的返回值.

當函式當作資料處理時,它將顯式地攜帶與定義該函式的周圍環境相關的資訊.這將直接影響到函式中自由變數的繫結方式.

#foo.py

x = 1

defcallfunc

(func):

return func()

#test.py

import foo

x = 2

defhello

():print

"hello.py x = %d"%x

foo.callfunc(hello) #hello.py x = 2,hello函式用的是test.py中x的值

foo.callfunc(hello)中的hello將組成hello()函式的語句與這些語句的變數及其執行環境打包在一起,此時得到的物件稱為閉包.

使用巢狀函式時,閉包將捕捉內部函式執行所需的整個環境.

#foo.py

x = 1

defcallfunc

(func):

return func()

#test.py

import foo

defbar

(): x = 2

defhello

():print

"hello.py x = %d"%x

foo.callfunc(hello)

bar() #hello.py x = 2

編寫惰性求值或延遲求值的**時,閉包和巢狀函式會發揮很大的作用.

def

bar():

x = 2

defhello

():print

"hello.py x = %d"%x

return hello

cnt = bar()

print cnt #

cnt() #hello.py x = 2

bar()並沒有左任何有意義的計算,它只是建立了hello函式,但是並未呼叫.

如果需要在一系列函式中保持某個狀態,使用閉包是一種非常高效的方式.

def

fun():

l =

defadd_num

(num = 0):

return l

return add_num

n = fun()

for i in range(3):

v = n(i)

print v

if len(v) > 10:

break

'''result:

[0][0, 1]

[0, 1, 2]

'''

保留了l的狀態.

閉包會捕捉內部函式的環境,因此可以用來包裝現有的函式,以便增加函式額外的功能.裝飾器就是利用的此特徵.((

Python 函式物件與閉包

函式物件指的是函式可以被當做 資料 來處理,具體可以分為四個方面的使用。def index print from index a index a def foo x,y,func print x,y func def bar print from bar foo 1,2,bar 1 2 from b...

函式物件與閉包

函式物件指的是函式可以被當做 資料 來處理 1.函式可以被引用 def add x,y return x y func add func 1,2 32.函式可以當做引數傳遞 def foo x,y,func return func x,y foo 1,2,add 33.函式可以當做返回值使用 傳參的...

python 閉包函式 python函式物件和閉包

一 函式物件 函式物件指的是函式可以被當做 資料 來處理,具體可以分為四個方面的使用,我們如下 1.1 函式可以被引用 def add x,y return x y func add func 1,2 1.2 函式可以作為容器型別的元素 dic dicdic add 1.3 函式可以作為引數傳入另外...