python编程(巧用装饰器)

栏目: Python · 发布时间: 8年前

内容简介:python编程(巧用装饰器)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

以前没有用过装饰器,也不知道它有什么用。直到最近写了一个log函数,在直到原来 python 的装饰器可以这么方便。

1、原来debug消息的写法

假设有一个process函数,原来是这么写的,

def process(*arg,  **dic):
    pass

后面,我们为了确认这个函数是否被调用了,那么可以这么写,

def process(*arg,  **dic):
    print 'Enter function process'

2、引入装饰器

用上面那种print的方法没有什么问题,但是总是觉得非常麻烦,其实我们可以用一个装饰器来解决。

def log(func):
    def wrapper(*arg, **dic):
        print 'Enter function ' + func.__name__
        return func(*arg, **dic) 
    return wrapper

3、使用装饰器

看上去上面就是一个普通的函数,没有什么特别之处。但是,它怎么使用呢,其实很简单,

@log
def process(*arg,  **dic):
    print arg, dic

有了这么一个装饰器之后,那么process函数在被调用的时候,就会默认调用log函数,从而打印相关的内容。

4、定制打印的消息级别

上面的log函数虽然也能使用,但是总觉得不如分层打印好。一个调试函数,按道理来说,应该是按照info、warning、debug、error级别来分层打印的。所以,按照这个要求,我们也可以定制自己的消息打印函数。

def debug_log(level):
    def debug_wrapper(func):
        def wrapper(*arg, **dic):
            if (1 == level):
                print 'Enter function ' + func.__name__
            return func(*arg, **dic) 
        return wrapper
    return debug_wrapper

同样,使用也非常容易,我们只需要在装饰器内填入参数就可以了,

@debug_log(level = 1)
def process(*arg,  **dic):
    print arg, dic

5、完整范例

最后,我们给出整个范例代码。希望大家可以在此基础上多多练习。

#!/usr/bin/python

import os
import sys
import re

'''
debug_log function
'''
def debug_log(level):
    def debug_wrapper(func):
        def wrapper(*arg, **dic):
            if (1 == level):
                print 'Enter function ' + func.__name__
            return func(*arg, **dic) 
        return wrapper
    return debug_wrapper


def log(func):
    def wrapper(*arg, **dic):
        print 'Enter function ' + func.__name__
        return func(*arg, **dic) 
    return wrapper

'''
real function
'''
@debug_log(level = 1)
def process(*arg,  **dic):
    print arg, dic

'''
file entry
'''
def main():
    process(1, 2, a=1)

if __name__ == '__main__':
    main()

以上所述就是小编给大家介绍的《python编程(巧用装饰器)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Spring Into HTML and CSS

Spring Into HTML and CSS

Molly E. Holzschlag / Addison-Wesley Professional / 2005-5-2 / USD 34.99

The fastest route to true HTML/CSS mastery! Need to build a web site? Or update one? Or just create some effective new web content? Maybe you just need to update your skills, do the job better. Welco......一起来看看 《Spring Into HTML and CSS》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具