python装饰器

本文参考了http://docs.pythontab.com/interpy
装饰器的实质是把函数当做参数传递给另一个函数(装饰函数)并返回。 先看一个简单的例子:

from functools import wraps

def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logit
def addition_func(x):
   """Do some math."""
   return x + x


result = addition_func(4)
# Output: addition_func was called

再看下带参数的装饰器:

def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile,并写入内容
            with open(logfile, 'a') as opened_file:
                # 现在将日志打到指定的logfile
                opened_file.write(log_string + '\n')
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator

@logit(logfile='func2.log')
def myfunc2():
    pass

myfunc2()
posted @ 2016-12-10 16:54  leesea  阅读(143)  评论(0)    收藏  举报