栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python基础知识—装饰器(Decorator)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python基础知识—装饰器(Decorator)

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/444262.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号