python裝飾器就是用於拓展原來函數功能的一種函數,這個函數的特殊之處在於它的返回值也是一個函數,使用python裝飾器的好處就是在不用更改原函數的代碼前提下給函數增加新的功能。 3.1 定義裝飾器,定義函數。 def xxx(): 函數體 3.2 應用裝飾器 在需要使用的函數、方法上@xxx即可 ...
python裝飾器就是用於拓展原來函數功能的一種函數,這個函數的特殊之處在於它的返回值也是一個函數,使用python裝飾器的好處就是在不用更改原函數的代碼前提下給函數增加新的功能。
3.1 定義裝飾器,定義函數。
def xxx():
函數體
3.2 應用裝飾器
在需要使用的函數、方法上@xxx即可。
註意:只要函數應用裝飾器,那麼函數就被重新定義,重新定義為:裝飾器的內層函數。
裝飾器含無參數的示例:

1 def outer(func):
2 def inner():
3 print('hello')
4 print('hello')
5 print('hello')
6 #原f1函數
7 r = func() # r = None
8 print('end')
9 print('end')
10 print('end')
11 reture r
12 reture inner
13
14 @outer
15 def f1():
16 return "f1"
17
18 f1() #調用者
19
20 #原理:
21 #1、執行outer函數,並且將下麵的函數名,當做參數,即f1 = func
22 #2、將outer的返回值重新賦值給f1 = outer的返回值
23 #3、新的f1函數 = inner
24
25 """
26 輸出結果:
27 hello
28 hello
29 hello
30 f1
31 end
32 end
33 end
34 """
View Code
裝飾器含傳遞兩個參數的示例:

1 def outer(func):
2 def inner(a1, a2): #傳遞兩個參數
3 print("123")
4 ret = func(a1, a2) #傳遞兩個參數
5 print("456")
6 return ret
7 reture inner
8
9 @outer
10 def index(a1, a2):
11 print("操作很複雜")
12 return a1 + a2
13
14 index(1, 2) #調用者
View Code
裝飾器含N個參數的函數示例:
註意:一個函數是可以應用多個裝飾器。多個裝飾器時先執行最外層的裝飾器。

1 def outer(func):
2 def inner(*arg, **kwargs): #可接收多個參數
3 print("123")
4 ret = func(*arg, **kwargs) #可接收多個參數
5 print("456")
6 return ret
7 reture inner
8
9 @outer
10 def f1(arg): #傳遞一個參數
11 print("我傳遞了一個參數")
12 reture "f1"
13
14 @outer
15 def index(a1, a2): #傳遞兩個參數
16 print("我傳遞了一個參數")
17 return a1 + a2
18
19 @outer
20 def f2(a1, a2, a3):
21 print("我傳遞三個參數")
22 return "f2"
23
24
25 f1(123) #調用者傳遞一個參數
26 index(1, 2) #調用者傳遞兩個參數
27 f2(1, 2, 3) #調用者傳遞三個參數
View Code