装饰器是python的一个重要部分,作用是可以在不改变原函数功能的基础上来对原函数进行功能的升级。就像人穿衣服一样。。。
装饰器在python中的使用
在程序中通常通过@来进行装饰器的实现如:
def decorator_a(func):
print ('Get in decorator_a')
def inner_a(*args, **kwargs):
print ('Get in inner_a')
return func(*args, **kwargs)
return inner_a
#@decorator_a
def f(x):
print ('Get in f')
return x * 2
以上代码实现了用函数decorator_a(func) 来装饰函数f() 运行f(1)后结果如图:
实现过程就相当于将函数f() 作为参数传入decorator_a(func) 函数,然后执行函数decorator_a(func) 返回的inner_a() 函数,如:
c = decorator_a(f)
c(1)
将f() 作为参数传入decorator_a(fun) 将返回函数赋予c 然后执行c(1) 执行结果为:
多个装饰器实现原理
以单个装饰器类似,当一个函数拥有多个装饰器后,装饰器的装饰顺序为由里到外 来进行装饰。如:
def decorator_a(func):
print ('Get in decorator_a')
def inner_a(*args, **kwargs):
print ('Get in inner_a')
return func(*args, **kwargs)
return inner_a
def decorator_b(func):
print ('Get in decorator_b')
def inner_b(*args, **kwargs):
print ('Get in inner_b')
return func(*args, **kwargs)
return inner_b
@decorator_b
@decorator_a
def f(x):
print ('Get in f')
return x * 2
f(1)
函数f() 拥有@decorator_b 与 @decorator_a 两个装饰器,当执行f(1) 时,结果如下:
首先函数将f()作为参数进入执行装饰器decorator_a() 函数中的打印内容,然后返回inner_a函数,将inner_a 函数作为参数进入decorator_b()装饰器执行decorator_b() 中的打印并返回inner_b ,当运行f(1) 时,相当于运行了inner_b(1) 函数,执行里面的打印内容并运行传入的func 即inner_a 函数,执行inner_a 中的打印然后执行装饰器decorator_a传入的参数func 即 f() 然后返回。当去掉上面例子中f() 函数的装饰器后改用函数调用的方式改写为参数调用的方式如下:
c = decorator_a(f)
d = decorator_b(c)
d(1)
执行结果如下:
以上就是我对python装饰器的一些理解,有错误的地方希望各位大牛多多指点。感谢