Python基础知识—装饰器(Decorator)
1、装饰器的作用
- 当有很多Function都要做些前置或者后置的工作时,我们可以使用装饰器统一处理
2、使用装饰器
- 写函数时,经常会出现,一个函数调用另一个函数的现象
def inner_fn(name):
print(name + " say I'm in")
def outer_fn(name):
inner_fn(name)
print(name + " say I'm out")
outer_fn("wgt")
wgt say I'm in
wgt say I'm out
- 而且有时,前后都会调用函数处理
def inner_pre_fn(name):
print(name+"say I'm in_pre")
def inner_post_fn(name):
print(name+"say I'm in_post")
def outer_fn(name):
inner_pre_fn(name)
print(name+"say I'm out")
inner_post_fn(name)
outer_fn("wgt")
wgt say I'm in_pre
wgt say I'm out
wgt say I'm in_post
- 使用装饰器
def decorator(fn, name):
print(name + " say I'm in")
return fn(name)
def outer_fn(name):
print(name + " say I'm out")
decorator(outer_fn, "wgt")
wgt say I'm in
wgt say I'm out
通过上述代码可以发现,一个函数是可以当作参数传入另一个函数的。
- 装饰器有一个特别的写法,就是在你想要修饰的函数上面写上
@decorate
,也就是@+装饰器名字
def decorator(fn):
def wrapper(name):
print(name + " say I'm in")
return fn(name)
return wrapper
@decorator
def outer_fn(name):
print(name + " say I'm out")
outer_fn("wgt")
wgt say I'm in
wgt say I'm out
- 前后都修饰
def decorator(fn):
def wrapper(name):
print(name + " say I'm in")
res = fn(name)
print(name+"say I'm in_post")
return res
return wrapper
@decorator
def outer_fn(name):
print(name + " say I'm out")
outer_fn("wgt")
wgt say I'm in
wgt say I'm out
wgtsay I'm in_post
3、总结
- 当要对很多函数做同样的装饰时,可以使用装饰器来实现
实例:验证一个用户有没有权限使用这个函数:
def authorization(fn):
def check_and_do(name):
if name != "wgt":
print(name + " has no right!")
return
res = fn(name)
return res
return check_and_do
@authorization
def outer1(name):
print(name + " outer1")
@authorization
def outer2(name):
print(name + " outer2")
@authorization
def outer3(name):
print(name + " outer3")
outer1("wgf")
outer2("qqq")
outer3("wgt")
wgf has no right!
qqq has no right!
wgt outer3
参考:莫烦Python