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()

输出

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  

场景

账号验证

日志

def use_logging(func):
    def wrapper(*args):
        logging.warning("%s is running" % func.__name__)
        start = time.time()
        result = func(*args)  # 把 foo 当做参数传递进来时,执行func()就相当于执行foo()
        end = time.time()
        logging.warning("%s is END, cost:%s ms" % (func.__name__, end - start))
        return result

    return wrapper


@use_logging
def foo(name):
    print('i am :', name)

foo("jihite")

 

参考

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

 
posted @ 2019-07-23 23:32  jihite  阅读(179)  评论(0编辑  收藏  举报