python 函数装饰器

一笑奈何 提交于 2020-02-28 07:11:25

举个例子

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

 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!