python --装饰器内容讲解

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

猜你喜欢

转载自www.cnblogs.com/june-L/p/11614343.html