zoukankan      html  css  js  c++  java
  • python-装饰器

    python装饰器(Decorators)

    装饰器让你在一个函数的前后去执行代码。

    一切皆对象

    python中的函数:

    def hi(name="yasoob"):
        return "hi " + name
     
    print(hi())
    # output: 'hi yasoob'
     
    # 我们甚至可以将一个函数赋值给一个变量,比如
    greet = hi
    # 我们这里没有在使用小括号,因为我们并不是在调用hi函数
    # 而是在将它放在greet变量里头。我们尝试运行下这个
     
    print(greet())
    # output: 'hi yasoob'
     
    # 如果我们删掉旧的hi函数,看看会发生什么!
    del hi
    print(hi())
    #outputs: NameError
     
    print(greet())
    #outputs: 'hi yasoob'
    

    在函数中定义函数

    从函数中返回函数

    将函数作为参宿传给另一个函数

    装饰器蓝本规范

    from functools import wraps
    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 func():
        return("Function is running")
     
    can_run = True
    print(func())
    # Output: Function is running
     
    can_run = False
    print(func())
    # Output: Function will not run
    
    注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
    

    使用场景

    授权(Authorization)

    装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:

    from functools import wraps
     
    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()
            return f(*args, **kwargs)
        return decorated
    

    日志(Logging)

    日志是装饰器运用的另一个亮点

    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
    

    带参数的装饰器

    在函数中嵌入装饰器

  • 相关阅读:
    20189207《网络攻防实践》第一周作业
    事件冒泡
    链接分类
    JS:offsetWidth\offsetleft
    JS alert()、confirm()、prompt()的区别
    this用法
    事件绑定
    clippath
    浅谈正则
    C++大师Lippman:我对中国程序员的忠告(转载)
  • 原文地址:https://www.cnblogs.com/zhangtao-0001/p/14797946.html
Copyright © 2011-2022 走看看