python 閉包和裝飾器

2021-08-21 17:54:14 字數 2529 閱讀 5337

# 閉包的寫法,兩層函式的巢狀,外部函式返回內部函式的引用,外層函式都帶引數

def 外層函式的名稱(引數):

def 內層函式的名稱():

pass

return 內層函式的引用

def

set_fun

(func):

func = 254

defcall_fun

():nonlocal func # 修改外層函式的值,並且內部函式有外部函式相同的變數名

print(func)

func = 100

return call_fun

fun = set_fun(123)

fun()

建立乙個閉包(終級版)

@xx裝飾你要裝飾的函式

def

set_fun

(func):

defcall_fun

(*args,**kwargs):

return func(*args,**kwargs)

return call_fun

@set_fun

deftest

():pass

案例

# 定義函式:完成包裹資料

defmakebold

(fn):

def():

return

"" + fn() + ""

# 定義函式:完成包裹資料

defmakeitalic

(fn):

def():

return

"" + fn() + ""

@makebold

deftest1

():return

"hello world-1"

@makeitalic

deftest2

():return

"hello world-2"

@makebold

@makeitalic

deftest3

():return

"hello world-3"

print(test1())

print(test2())

print(test3())

執行結果:

hello world-1b>

hello world-2i>

hello world-3i>

b>

引入日誌

函式執行時間統計

執行函式前預備處理

執行函式後清理功能

許可權校驗等場景

快取

# 作業要求

# 設計裝飾器

# 計算某函式的執行次數,使用者行為分析

# 計算某函式的執行時間,優化

import random

import time

# 定義裝飾器1,計算次數

defout_fun1

(func):

count = 0

definner_func

(): func()

nonlocal count

# global count

count += 1

return count

return inner_func

# 定義裝飾器2,計算時間

defout_fun2

(func):

definner_func

(): start = time.time()

func()

end = time.time()

return end - start

return inner_func

@out_fun1

defdemo

(): a = 0

for x in range(1, 100001):

a += x

# print('計算100000以內的累加,結果為:', a)

@out_fun1

defdemo1

(): a = 1

for x in range(1,101):

a *= x

# print('計算1-100累積,結果為:', a)

@out_fun2

deftest

():for x in range(100):

index = random.randint(90, 100)

if index % 2 == 0:

count = demo()

print('第', count, '次執行demo函式')

else:

count = demo1()

print('demo1函式,第', count, '次執行')

print('共用時', test())

python裝飾器和閉包

下面幾個部落格有裝飾器的講解,也包含了裝飾器幾種情況的例子,比如說被裝飾的函式帶引數,裝飾器本身帶引數等。理解python中的裝飾器 python裝飾器學習 例子 其實裝飾器跟設計模式中的裝飾器模式基本一樣,就是在已有的函式上新增新的功能,這也是自己對裝飾器的一點簡陋的理解了。下面是自己寫的簡單例子...

python閉包和裝飾器

要理解裝飾器,就要明白閉包 要明白閉包,首先就要從高階函式和作用域說起 說道作用域,一般會談到legb規則。所謂的legb l locals,當前命名空間 區域性作用域 e enclosing,外部函式的命名空間 外部作用域 g global,全域性的命名空間 b bulit in,內建的命名空間平...

Python 閉包和裝飾器

裝飾器函式裝飾器 類裝飾器 functools.wraps 簡介def outer func number definner func inner number return number inner number return inner func 給外部函式複製,20傳遞給number,並返回內...