Python中的裝飾器理解

2021-08-15 08:35:57 字數 2156 閱讀 6926

主要記住兩個例子就好:

1.裝飾器含有不確定引數

需要注意:

1.裝飾器的引數func為函式,裝飾器內部函式_deco的引數*args, **kwargsfunc函式傳入的不確定性變數。

2.裝飾器以輸出的函式作為形參,返回內部自定義的函式;內部自定義的函式返回形參傳入的函式;所以可認為,裝飾器傳入函式,返回的還是這個函式,只不過是處理過後的函式。

def deco(func):

def _deco(*args, **kwargs):

print("before %s called." % func.__name__)

ret = func(*args, **kwargs)

print(" after %s called. result: %s" % (func.__name__, ret))

return ret

return _deco

@deco

def myfunc(a, b):

print(" myfunc(%s,%s) called." % (a, b))

return a+b

@deco

def myfunc2(a, b, c):

print(" myfunc2(%s,%s,%s) called." % (a, b, c))

return a+b+c

myfunc(1, 2)

myfunc(3, 4)

myfunc2(1, 2, 3)

myfunc2(3, 4, 5)

輸出結果:

before myfunc called.

myfunc(1,2) called.

after myfunc called. result: 3

before myfunc called.

myfunc(3,4) called.

after myfunc called. result: 7

before myfunc2 called.

myfunc2(1,2,3) called.

after myfunc2 called. result: 6

before myfunc2 called.

myfunc2(3,4,5) called.

after myfunc2 called. result: 12

2.帶引數的裝飾器

需要明白的是:

1.deco(arg)_deco(func)的括號裡帶的是變數還是函式;

2.遇到帶引數的裝飾器,可以去掉最外層def deco(arg):把他當成普通裝飾器看待;

def deco(arg):

def _deco(func):

def __deco():

print("before %s called [%s]." % (func.__name__, arg))

func()

print(" after %s called [%s]." % (func.__name__, arg))

return __deco

return _deco

@deco("mymodule")

def myfunc():

print(" myfunc() called.")

@deco("module2")

def myfunc2():

print(" myfunc2() called.")

myfunc()

myfunc2()

返回結果:

before myfunc called [mymodule].

myfunc() called.

after myfunc called [mymodule].

before myfunc2 called [module2].

myfunc2() called.

after myfunc2 called [module2].

python中的裝飾器理解

python裝飾器 fuctional decorators 就是用於拓展原來函式功能的一種函式,目的是在不改變原函式名 或類名 的情況下,給函式增加新的功能。這個函式的特殊之處在於它的返回值也是乙個函式,這個函式是內嵌 原 函式的函式。之前拓展函式的做法是侵入原函式進行拓展修改,例如 原始函式 i...

python裝飾器理解 python裝飾器理解

裝飾器 在不改變原函式的 和呼叫方法的基礎上,給原函式增加額外的功能 理解宣告 為了方便理解,以下例子採用最簡潔的函式和新增的功能 給原函式新增乙個執行時間 import time def timer func def inner func return inner timer func timer...

python裝飾器 理解Python裝飾器

在python中,對於乙個函式,若想在其執行前後做點什麼,那麼裝飾器是再好不過的選擇,話不多說,上 usr bin env coding utf 8 script 01.py author howie from functools import wraps def decorator func wr...