• 装饰器函数和装饰器类


    1.装饰器函数就是把函数作为参数传给一个函数

    # def a_new_decorater(a_func):
    # def wrapTheFunction():
    # print("I am doing some boring work before executing a_func()")
    # a_func()
    # print("I am doing some boring work after executing a_func()")
    # return wrapTheFunction
    # def a_function_requiring_decoration():
    # print("I am the function which needs some decoration to remove my foul smell")
    # a_function_requiring_decoration()
    # a_function_requiring_decoration = a_new_decorater(a_function_requiring_decoration)
    # a_function_requiring_decoration()
    # @a_new_decorater
    # def a_function_requiring_decoration():
    # """Hey you!Decorate me!"""
    # print("I am the function which needs some decoration to" "remove my foul smell")
    # a_function_requiring_decoration()
    #
    # a_function_requiring_decoration = a_new_decorater(a_function_requiring_decoration)
    from functools import wraps
    # def a_new_decorator(a_func):
    # @wraps(a_func)
    # def wrapTheFunction():
    # print("I am doing some boring work before executing a_func()")
    # a_func
    # print("I am doing some boring work after executing a_func()")
    # return wrapTheFunction
    # @a_new_decorator
    # def a_function_requiring_decoration():
    # """Hey yo!Decorate me!"""
    # print("I am the function which needs some decoration to" "remove my foul smell")
    # print(a_function_requiring_decoration.__name__)
    # def decorator_name(f):
    # @wraps(f)
    # def decorated(*args,**kwargs):
    # if not can_run:
    # return "Function will not run"
    # return f(*args,**kwargs)
    # return decorated
    # @decorator_name
    # def fun():
    # return ("Function is running")
    # can_run = True
    # print(fun())
    # can_run = False
    # print(fun())
    #认证
    # def requires_auth(f):
    # @wraps(f)
    # def decorated(*args,**kwargs):
    # auth = request.authorization
    # if not auth or not check_auth(auth.username,auth.password):
    # authenticate(0)
    # return f(*args,**kwargs)
    # return decorated
    #日志
    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)
    # print(result)
    #一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()。
    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 + ' ')
    # 现在,发送一个通知
    self.notify()
    return func(*args, **kwargs)
    return wrapped_function

    def notify(self):
    # logit只打日志,不做别的
    pass
    # 这个实现有一个附加优势,在于比嵌套函数的方式更加整洁,而且包裹一个函数还是使用跟以前一样的语法:
    @logit()
    def myfunc1():
    pass
    # 现在,我们给logit创建子类,来添加email的功能(虽然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
    # 从现在起,@email_logit将会和@logit产生同样的效果,但是在打日志的基础上,还会多发送一封邮件给管理员。
  • 相关阅读:
    车联网场景中的 MQTT 协议
    MQTT 遗嘱消息(Will Message)的使用
    为什么烧写SD卡的 image 总是报错?
    【友晶科技Terasic】无法下载Quartus软件,每次登录后又跳回到下载页面
    three.js在调整相机角度时导致的图形显示
    JOIG 2022 题解
    JOI 2021/2022 二次予選 题解
    Codeforces Round #769 (Div. 2) 题解
    WC2022 游记
    树莓派安装软件包时出现的很多依赖问题的解决
  • 原文地址:https://www.cnblogs.com/Jt00/p/7519121.html
Copyright © 2020-2023  润新知