python 装饰器

2023-05-16

1.装饰器

装饰器(Decorators)是Python的一个重要部分。简单地说:他们是修改其他函数的功能的函数。他们有助于让我们的代码更简短,也更Pythonic(Python范儿)。大多数初学者不知道在哪儿使用它们,所以我将要分享下,哪些区域里装饰器可以让你的代码更简洁。

2.一切皆对象

首先我们来理解下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'


3.在函数中定义函数

刚才那些就是函数的基本知识了。我们来让你的知识更进一步。在Python中我们可以在一个函数中定义另一个函数:

def hi(name="yasoob"):
    print("now you are inside the hi() function")

    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    print(greet())
    print(welcome())
    print("now you are back in the hi() function")

hi()
#output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function

# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:

greet()
#outputs: NameError: name 'greet' is not defined

那现在我们知道了可以在函数中定义另外的函数。也就是说:我们可以创建嵌套的函数。现在你需要再多学一点,就是函数也能返回函数。

4.从函数中返回函数

其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:

def hi(name="yasoob"):
    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    if name == "yasoob":
        return greet
    else:
        return welcome

a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>

#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个

print(a())
#outputs: now you are in the greet() function

再次看看这个代码。在if/else语句中我们返回greetwelcome,而不是greet()welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

你明白了吗?让我再稍微多解释点细节。

当我们写下a = hi()hi()会被执行,而由于name参数默认是yasoob,所以函数greet被返回了。如果我们把语句改为a = hi(name = "ali"),那么welcome函数将被返回。我们还可以打印出hi()(),这会输出now you are in the greet() function

5.将函数作为参数传给另一个函数

def hi():
    return "hi yasoob!"

def doSomethingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())

doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
#        hi yasoob!

现在你已经具备所有必需知识,来进一步学习装饰器真正是什么了。装饰器让你在一个函数的前后去执行代码。

6.你的第一个装饰器

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

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



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 装饰器 的相关文章

  • Pandas apply 与 np.vectorize 从现有列创建新列的性能

    我正在使用 Pandas 数据框 并希望创建一个新列作为现有列的函数 我还没有看到关于之间速度差异的很好的讨论df apply and np vectorize 所以我想我会在这里问 熊猫apply 功能很慢 根据我的测量 在一些实验中如下
  • DataFrame 在函数内部修改

    我面临一个我以前从未观察到的函数内数据帧修改的问题 有没有一种方法可以处理这个问题 以便初始数据帧不被修改 def test df df tt np nan return df dff pd DataFrame data 现在 当我打印时d
  • Python:记录垃圾收集器

    我有一个 python 应用程序 有一些性能问题 我想将垃圾收集器的事件 特别是何时调用 添加到我的日志中 是否可以 thanks http docs python org library gc html gc set debug http
  • Python 在 chroot 中运行时出现错误

    我尝试在 chroot 中运行一些 Python 程序 但出现以下错误 Could not find platform independent libraries
  • 底图上的子图

    我有一张英国地图和 121 个地点 每个地点有 3 个值 我想绘制 121 个位置中每个位置的三个值的小条形图 目前 这些值绘制为markersize属性 看起来像这样 密集恐惧症情节 https i stack imgur com 5fv
  • Python 遍历目录树的方法是什么?

    我觉得分配文件和文件夹并执行 item 部分有点黑客 有什么建议么 我正在使用Python 3 2 from os import from os path import def dir contents path contents list
  • 将 API 数据存储到 DataFrame 中

    我正在运行 Python 脚本来从 Interactive Brokers API 收集金融市场数据 连接到API后 终端打印出请求的历史数据 如何将数据保存到数据帧中而不是在终端中流式传输 from ibapi wrapper impor
  • conda 无法从 yml 创建环境

    我尝试运行下面的代码来从 YAML 文件创建虚拟 Python 环境 我在 Ubuntu 服务器上的命令行中运行代码 虚拟环境名为 py36 当我运行下面的代码时 我收到下面的消息 环境也没有被创建 这个问题是因为我有几个必须使用 pip
  • html 解析器 python

    我正在尝试解析一个网站 我正在使用 HTMLParser 模块 问题是我想解析第一个 a href 评论后 但我真的不知道该怎么做 所以我在文档中发现有一个函数叫做handle comment 但我还没有找到如何正确使用它 我有以下内容 i
  • 为 Networkx 图添加标题?

    我希望我的代码创建一个带有标题的图 使用下面的代码 可以创建绘图 但没有标题 有人可以告诉我我做错了什么吗 import pandas as pd import networkx as nx from networkx algorithms
  • 网页抓取 - 前往第 2 页

    如何访问数据集的第二页 无论我做什么 它都只返回第 1 页 import bs4 from urllib request import urlopen as uReq from bs4 import BeautifulSoup as sou
  • 错误:无法访问文件“$libdir/plpython2”:没有这样的文件或目录

    我正在运行 postgresql 9 4 PostgreSQL 9 4 4 on x86 64 unknown linux gnu compiled by gcc GCC 4 1 2 20070626 Red Hat 4 1 2 14 64
  • pip 安装软件包两次

    不幸的是我无法重现它 但我们已经见过几次了 pip 将一个软件包安装两次 如果卸载第一个 第二个就会可见并且也可以被卸载 我的问题 如果一个包安装了两次 如何用 python 检查 背景 我想编写一个测试来检查这一点 devOp Updat
  • 一起使用 Flask 和 Tornado?

    我是以下的忠实粉丝Flask 部分是因为它很简单 部分是因为它有很多扩展 http flask pocoo org extensions 然而 Flask 是为了在 WSGI 环境中使用而设计的 而 WSGI 不是非阻塞的 所以 我相信 它
  • 如何在 Python 中从 HTML 页面中提取 URL [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我必须用Python 编写一个网络爬
  • Django 接受 AM/PM 作为表单输入

    我试图弄清楚如何使用 DateTime 字段在 Django 中接受 am pm 作为时间格式 但我遇到了一些麻烦 我尝试在 forms py 文件中这样设置 pickup date time from DateTimeField inpu
  • 在Python中从日期时间中减去秒

    我有一个 int 变量 它实际上是秒 让我们调用这个秒数X 我需要得到当前日期和时间 以日期时间格式 减去的结果X秒 Example If X是 65 当前日期是2014 06 03 15 45 00 那么我需要得到结果2014 06 03
  • 在Python 3.2中,我可以使用http.client打开并读取HTTPS网页,但urllib.request无法打开同一页面

    我想打开并阅读https yande re https yande re with urllib request 但我收到 SSL 错误 我可以使用以下方式打开并阅读页面http client用这个代码 import http client
  • 从数据集的给定日期范围中提取属于一天的数据

    我有一个数据集 日期范围为 2018 年 1 月 12 日到 8 月 3 日 其中包含一些值 维数为my df数据框是 my df shape 9752 2 每行包含半小时频率 第一行开始于2018 01 12 my df iloc 0 D
  • 从 pandas 数据框中绘制堆积条形图

    我有数据框 payout df head 10 复制以下 Excel 绘图的最简单 最智能和最快的方法是什么 我尝试过不同的方法 但无法让一切都到位 Thanks 如果您只想要一个堆积条形图 那么一种方法是使用循环来绘制数据框中的每一列 并

随机推荐

  • java11的下载与安装及环境配置

    java11的下载与安装及环境配置 下载Java11 直达下载链接 xff1a https www oracle com technetwork java javase downloads jdk11 downloads 5066655 h
  • 静态页面中报 Blocked a frame with origin "null" from accessing a cross-origin frame.原因

    1 报错的内容是 xff1a 2 从编辑器中打开没有问题 xff0c 但是直接在文件中打开网页 xff0c 在点击一些事件时 xff0c 就会出现这种问题 xff0c 其实这不是跨域问题 xff0c 因为都没有放到服务器上 xff0c 这只
  • IDEA maven项目中刷新依赖的两种方法

    前言 IDEA maven项目中刷新依赖分为自动刷新 和 手动刷新 两种 xff01 自动刷新 xff1a File Settings 手动刷新 xff1a
  • CMAKE Opencv配置

    本人使用场景 xff1a 项目中别人使用CMAKE维护的一个项目代码 xff0c 里面没有配置Opencv xff0c 自己使用的时候希望配置上 xff0c 尝试直接在项目中利用项目属性进行修改 xff08 未成功 xff0c 有经验的同学
  • Windows下配置Hadoop环境(全过程)

    首先到官方下载官网的hadoop2 7 7 链接如下 https mirrors tuna tsinghua edu cn apache hadoop common 找网盘的hadooponwindows master zip 链接如下 h
  • ARM立即寻址中有效立即数的计算

    前言 感觉这方面的计算参考书上也讲的比较模糊 xff0c 在这里分享一下计算的方法 立即数寻址有效数的计算 xff08 一 xff09 ARM立即数寻址的指令格式 xff08 二 xff09 例1 汇编指令 xff1a mov R0 0x0
  • mysql8.0安装后设置密码

    mysql8 0安装后密码调整 创建密码策略 xff1a INSTALL COMPONENT file component validate password 查看是否创建成功 xff0c 执行后显示如下内容标识密码策略安装成功 属性值可修
  • C++读取文件夹中的文件

    下面是一种简便的读取文件夹里所有子文件夹和文件的方法 xff0c 如果想读取子文件夹下所有文件 xff0c 可以递归一下 span class token macro property span class token directive
  • 树莓4B+samba+nextcloud搭建nas私有云

    文章目录 概述环境准备网络机械硬盘格式化及分区 Samba安装部署nextCloud安装部署docker安装安装相关容器配置及优化创建数据库next cloud注册错误提示 xff1a nextcloud install Error whi
  • linux 配置java环境变量 报错 `=': 不是有效的标识符

    linux 配置java环境变量 运行source etc profile时 报错 96 61 39 不是有效的标识符 解决办法 export JAVA HOME 61 usr local java jdk1 8 0 151 的 61 左右
  • Word 自带公式转为mathtype格式

    选中公式 xff0c 在公式中 xff0c 选择LaTeX 复制后 xff0c 插入mathtype公式中
  • 从头用脚分析FFmpeg源码 - avcodec_send_frame | avcodec_receive_packet

    avcodec send frame和avcodec receive packet 作用 相对应avcodec send packet avcodec receive frame而言 xff0c avcodec send frame xff
  • Debian系统解决中文乱码问题

    1 安装locales apt get install locales 2 设置语言选项 dpkg reconfigure locales 选择如下四项 xff1a zh CN GB2312zh CN GBK GBKzh CN UTF 8
  • raspbian-buster安装php7.3

    安装php sudo apt get install php7 3 fpm php7 3 curl php7 3 gd php7 3 mbstring php7 3 mysql php7 3 imap php7 3 opcache php7
  • Linux下查看服务器各硬件信息

    span class hljs comment 内存 span span class hljs preprocessor free m span span class hljs preprocessor cat proc meminfo s
  • Day2、Hive json_tuple性能比get_json_object更高吗?为什么?

    目录 一 执行过程 二 源码比较 三 实验论证 四 总结 在对离线任务进行优化时 xff0c 一般来说有两种思路 一是参数优化 xff0c 尽量提高CPU 内存利用率 xff0c 或者减少spill率 xff1b 二是SQL优化 xff0c
  • Ubuntu18.04下更改apt源

    任意版本的系统代号 xff1a Ubuntu 12 04 LTS 代号为precise Ubuntu 14 04 LTS 代号为trusty Ubuntu 15 04 代号为vivid Ubuntu 15 10 代号为wily Ubuntu
  • C语言中数的二进制、八进制、十进制以及十六进制表示及输出

    以十进制数163为例 xff1a 二进制的英文是Binary xff0c 简写为B或BIN xff0c 所以163 61 0b10100011 xff08 前面加上 0b 或 0B xff09 八进制的英文是Octal xff0c 简写为O
  • java-字符串数组排序

    问题 43 代码 xff1a 创建一个长度是8的字符串数组 使用8个长度是5的随机字符串初始化这个数组 对这个数组进行排序 xff0c 按照每个字符串的首字母排序 无视大小写 注1 xff1a 不能使用Arrays sort 要自己写 注2
  • python 装饰器

    1 装饰器 装饰器 Decorators 是Python的一个重要部分 简单地说 xff1a 他们是修改其他函数的功能的函数 他们有助于让我们的代码更简短 xff0c 也更Pythonic xff08 Python范儿 xff09 大多数初