Python进阶
  • 简介
  • 序
  • 译后感
  • 原作者前言
  • args 和 *kwargs
    • *args 的用法
    • **kwargs 的用法
    • 使用 args 和 *kwargs 来调用函数
    • 啥时候使用它们
  • 调试 Debugging
  • 生成器 Generators
    • 可迭代对象(Iterable)
    • 迭代器(Iterator)
    • 迭代(Iteration)
    • 生成器(Generators)
  • Map,Filter 和 Reduce
    • Map
    • Filter
    • Reduce
  • set 数据结构
  • 三元运算符
  • 装饰器
    • 一切皆对象
    • 在函数中定义函数
    • 从函数中返回函数
    • 将函数作为参数传给另一个函数
    • 你的第一个装饰器
      • 使用场景
      • 授权
      • 日志
    • 带参数的装饰器
      • 在函数中嵌入装饰器
      • 装饰器类
  • Global和Return
    • 多个return值
  • 对象变动 Mutation
  • slots魔法
  • 虚拟环境 Virtualenv
  • 容器 Collections
  • 枚举 Enumerate
  • 对象自省
    • dir
    • type和id
    • inspect模块
  • 推导式 Comprehension
    • 列表推导式
    • 字典推导式
    • 集合推导式
  • 异常
    • 处理多个异常
      • finally从句
      • try/else从句
  • 类
  • lambda表达式
  • 一行式
  • For - Else
    • else语句
  • 使用C扩展
    • CTypes
    • SWIG
    • Python/C API
  • open函数
  • 目标Python2+3
  • 协程
  • 函数缓存
    • Python 3.2+
    • Python 2+
  • 上下文管理器
    • 基于类的实现
    • 处理异常
    • 基于生成器的实现
  • 推荐阅读
  • 捐赠名单
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 装饰器

你的第一个装饰器

在上一个例子里,其实我们已经创建了一个装饰器!现在我们修改下上一个装饰器,并编写一个稍微更有用点的程序:

def a_new_decorator(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()
#outputs: "I am the function which needs some decoration to remove my foul smell"

a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()

a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

你看明白了吗?我们刚刚应用了之前学习到的原理。这正是python中装饰器做的事情!它们封装一个函数,并且用这样或者那样的方式来修改它的行为。现在你也许疑惑,我们在代码里并没有使用 @ 符号?那只是一个简短的方式来生成一个被装饰的函数。这里是我们如何使用 @ 来运行之前的代码:

@a_new_decorator
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()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()

#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

希望你现在对 Python 装饰器的工作原理有一个基本的理解。如果我们运行如下代码会存在一个问题:

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

这并不是我们想要的!Ouput 输出应该是 “a_function_requiring_decoration”。这里的函数被 warpTheFunction 替代了。它重写了我们函数的名字和注释文档(docstring)。幸运的是 Python 提供给我们一个简单的函数来解决这个问题,那就是 functools.wraps。我们修改上一个例子来使用 functools.wraps:

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__)
# Output: a_function_requiring_decoration

现在好多了。我们接下来学习装饰器的一些常用场景。

蓝本规范:

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

上一页将函数作为参数传给另一个函数下一页使用场景

最后更新于3年前

这有帮助吗?