zoukankan      html  css  js  c++  java
  • 装饰器函数和装饰器类

    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产生同样的效果,但是在打日志的基础上,还会多发送一封邮件给管理员。
  • 相关阅读:
    MAC LAMP环境 php执行使用问题
    centos 服务器 安全设置
    Linux系统发现占用CPU达100%的进程并处理
    git 使用国内镜像 ,查看镜像更改情况
    mac安装composer
    MySql反向模糊查询
    Linux启动或重启网卡
    MAMP环境 nginx配置忽略index.php入口文件
    php 验证码生成 不保存的情况下 缩小图片质量
    KMP字符串模式匹配详解
  • 原文地址:https://www.cnblogs.com/Jt00/p/7519121.html
Copyright © 2011-2022 走看看