0
点赞
收藏
分享

微信扫一扫

python编程(巧用装饰器)

芥子书屋 2022-11-23 阅读 184

    以前没有用过装饰器,也不知道它有什么用。直到最近写了一个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()


举报

相关推荐

0 条评论