zoukankan      html  css  js  c++  java
  • 编写带参数decorator

    无参的@log装饰器:

    def log(f):
        def fn(x):
            print 'call ' + f.__name__ + '()...'
            return f(x)
        return fn
    

    发现对于被装饰的函数,log打印的语句是不能变的(除了函数名)。

    如果有的函数非常重要,希望打印出'[INFO] call xxx()...',有的函数不太重要,希望打印出'[DEBUG] call xxx()...',这时,log函数本身就需要传入'INFO'或'DEBUG'这样的参数,类似这样:

    @log('DEBUG')
    def my_func():
        pass
    

    把上面的定义翻译成高阶函数的调用,就是:

    my_func = log('DEBUG')(my_func)
    

    上面的语句看上去还是比较绕,再展开一下:

    log_decorator = log('DEBUG')
    my_func = log_decorator(my_func)
    

    上面的语句又相当于:

    log_decorator = log('DEBUG')
    @log_decorator
    def my_func():
        pass
    

    所以,带参数的log函数首先返回一个decorator函数,再让这个decorator函数接收my_func并返回新函数:

    def log(prefix):
        def log_decorator(f):
            def wrapper(*args, **kw):
                print '[%s] %s()...' % (prefix, f.__name__)
                return f(*args, **kw)
            return wrapper
        return log_decorator
    
    @log('DEBUG')
    def test():
        pass
    print test()
    

    执行结果:

    [DEBUG] test()...
    None
    
  • 相关阅读:
    01 Windows编程——Hello World
    图像处理基础知识
    集成IDE anaconda
    Python中的正则表达式
    Introduction of Machine Learning
    Linux命令——diff、patch
    sed & awk 概述
    Linux行编辑器——ed
    Linux命令——w、who、whoami、lastlog、last
    【问题】统计系统上有多少个用户
  • 原文地址:https://www.cnblogs.com/XXCXY/p/5182832.html
Copyright © 2011-2022 走看看