裝飾器2 高階函式 函式巢狀 閉包

2022-05-06 06:18:12 字數 2149 閱讀 9639

高階函式定義

1.函式接受的引數是乙個函式名

2.函式的返回值是乙個函式名

3.滿足上訴條件任意乙個,都可稱之為高階函式

1

deftest():

2print('

你好啊')3

defhigh_func(func):

4print('

高階函式')

5func()

6high_func(test)

7輸出:

8高階函式

9 你好啊

函式巢狀    在函式裡面在定義乙個函式

1

deffather(name):

2print('

from father %s

' %name)

3def

son():

4print('

from son')

5def

dahghter():

6print('

from daughter')

7dahghter()

8son()

9 father('a'

)10輸出:11

from

father a

12from

son13

from daughter

閉包:在乙個作用域裡放入定義變數,相當於打了乙個包

1

deftest(name):

2def

son():

3def

grandson():

4print('

我的名字是%s

'%name)

5grandson()

6son()

7 test('小明'

)8輸出:9 我的名字是小明

閉包的基本實現

1

import

time

2def

timmer(func):

3def

4 start_time =time.time()

5func()

6 stop_time =time.time()

7print('

程式執行時間%s

'%(stop_time-start_time))

8return

9def

fool():

10 time.sleep(3)

11print('

程式執行完了')

12 f =timmer(fool)

13f()

14 fool =timmer(fool)

15fool()

16輸出:

17程式執行完了

18 程式執行時間3.0032291412353516

19程式執行完了

20 程式執行時間3.003220796585083

新增裝飾器@timmer  結果

1

import

time

2def

timmer(func):

3def

4 start_time =time.time()

5func()

6 stop_time =time.time()

7print('

程式執行時間%s

'%(stop_time-start_time))

8return

9 @timmer #

相當於 fool = timmer(fool)

10def

fool():

11 time.sleep(3)

12print('

程式執行完了')

13#f = timmer(fool)14#

f()15

#fool = timmer(fool)16#

fool()

17fool()

18輸出:

19程式執行完了

20 程式執行時間3.0024335384368896

語法糖@             語法糖表示既好看又好用的語法

裝飾器 高階函式 閉包 函式巢狀

裝飾器 本質就是函式,作用是給其他函式新增新功能 1 不修改被修飾函式的源 2 不修改被修飾函式的呼叫方法 import time deftimmer func def args,kwargs start time time.time res func args,kwargs end time ti...

裝飾器的學習 初級版 高階函式,巢狀函式,閉包

裝飾器 本質是函式,功能是為其他函式新增附加功能 原則 1 不修改被修飾函式的源 2 不修改被修飾函式的呼叫方式 為了實現裝飾器的功能,需要了解3個概念 1。高階函式高階函式定義 函式接收的引數是乙個函式名 函式的返回值是乙個函式名 滿足上述條件的任意乙個,都稱為高階函式def foo print ...

190401裝飾器 高階函式 閉包

裝飾器本質是函式 為其他函式新增附加功能 不修改被修飾函式的源 不修改被修飾函式的呼叫方式 import time def timmer func start time time.time res func args,kwargs stop time time.time return res tim...