python Decrator

python Decrator,第1张

文章目录
  • Decorator

Decorator

装饰器

Python 函数装饰器

基本格式(函数形式):

def decorator_name(func):
    @warps(func) #保证函数名不发生改变,不这样写,函数名会变成装饰器的函数名
    def warpTheFunc():
        func()
    return warpTheFunc	
    
@decorator_name
def func():
    pass

@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

类的格式(推荐):

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) # 注意,这里返回的是func
        return wrapped_function # 注意,这里返回的是wrapped_function
 
    def notify(self):
        # logit只打日志,不做别的
        pass
    
@logit(logfile='func2.log')
def myfunc1():
    pass

#继承后的装饰器,多了发email的功能
class email_logit(logit):
    '''
    一个logit的实现版本,可以在函数调用时发送email给管理员
    '''
    def __init__(self, email='admin@myproject.com', *args, **kwargs):
        self.email = email
        super(email_logit, self).__init__(*args, **kwargs)
 
    def notify(self):
        # 发送一封email到self.email
        # 这里就不做实现了
        pass

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/717602.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-25
下一篇2022-04-25

发表评论

登录后才能评论

评论列表(0条)

    保存