首页 > 编程语言 > 详细

python 函数装饰器

时间:2019-07-24 01:15:59      阅读:188      评论:0      收藏:0      [点我收藏+]

举个例子

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

 

python 函数装饰器

原文:https://www.cnblogs.com/kaituorensheng/p/11235219.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!