装饰器decorator

def use_logging(func):
    def wrapper(*args,**kwargs):
        logging.warn("%s is running" % func.__name__)
        return func(*args,**kwargs)
    #元信息
    wrapper.__doc__ = func.__doc__
    wrapper.__name__ = func.__name__
    return wrapper

@use_logging
def foo():
    print "I am foo" 

@wrap保留元信息

from functools import wraps
def use_logging(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        logging.warn("%s is running" % func.__name__)
        return func(*args,**kwargs)
    #元信息
    return wrapper

类(class)的装饰器

from functools import wraps
class logit(object):
    def __init__(self,logfile="out.log"):
        self.logfile = logfile
    
    def __call__(self,func):
        @wraps(func)
        def wrapped_function(*args,**kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile并写入
            with open(self.logfile, 'a') as opened_file:
                # 现在将日志打到指定的文件
                opened_file.write(log_string + '\n')
            # 现在,发送一个通知
            self.notify()
            return func(*args,**kwargs)
        return wrapped_function     
        def notify(self):
            # logit只打日志,不做别的
            pass

继承装饰器

class email_logit(logit):
    '''
    一个logit的实现版本,可以在函数调用时发送email给管理员
    '''
    def __init__(self, email='[email protected]', *args, **kwargs):
        self.email = email
        super(logit, self).__init__(*args, **kwargs)

    def notify(self):
        # 发送一封email到self.email
        # 这里就不做实现了
        pass

From:http://docs.pythontab.com/interpy/decorators/deco_class/

你可能感兴趣的:(装饰器decorator)