加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python 函数装饰器

发布时间:2020-12-20 12:57:57 所属栏目:Python 来源:网络整理
导读:举个例子 def a_decorator(func): def wrapTheFunc(): print " before decorator " func() print " end decorator " return wrapTheFunc@a_decorator def a_func_need_decorator(): print " In a_func_need_decorator() " a_func_need_decorator() 输出 befo

举个例子

def a_decorator(func):
    def wrapTheFunc():
        print "before decorator"
        func()
        print "end decorator"

    return wrapTheFunc


@a_decorator
def a_func_need_decorator():
    print "In a_func_need_decorator()"


a_func_need_decorator()

输出

before decorator
In a_func_need_decorator()
end decorator

等价

不是很明白??

@a_decorator?

def a_func_need_decorator():

等价于

a_func_need_decorator = a_decorator(a_func_need_decorator)

修改下代码

def a_decorator(func):
    def wrapTheFunc():
        print "before decorator"
        func()
        print "end decorator"

    return wrapTheFunc


def a_func_need_decorator():
    print "In a_func_need_decorator()"


a_func_need_decorator = a_decorator(a_func_need_decorator)
a_func_need_decorator()

结果是一致的

什么?函数还可以作为对象传输

是的,举例

def test(a):
    print a


test2 = test
test2("hello")

输出

hello  

场景

账号验证

日志

?

参考

https://www.runoob.com/w3cnote/python-func-decorators.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读