python-装饰器骗局

2024-04-04 18:58
文章标签 python 装饰 骗局

本文主要是介绍python-装饰器骗局,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

装 饰 器 骗 局

Python 函数装饰器:https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器的本意:
加上装饰器—>除了自身功能还有被装饰的内容
不加装饰器—>只有自身的功能

先来看一个装饰器的使用范例:

#计算程序运算时间的装饰器 --- 需要有一个形参 接受待验证运行时间的函数
def get_time(func):def wrapper():import timestart = time.time()func()stop = time.time()print("执行时间", stop - start)return wrapper'''
怎么为对应的功能添加装饰器使用@语法糖  在被需要添加装饰器的功能上方 @装饰器的外部函数
'''
@get_time
def print_nine_table():for r in range(1, 10):for c in range(1, r + 1):print(f"{c} * {r} = {r*c}", end="\t")print()
print_nine_table()

在这里插入图片描述
在这里插入图片描述

装饰器----->原有函数功能增加 or 函数重构 ?

咱们先来看下 Python 中的函数的一些操作:

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

在函数中定义函数:

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

从函数中返回函数:

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 greetelse:return welcomea = hi()
print(a)
# outputs: <function greet at 0x7f2143c01500># 上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
# 现在试试这个print(a())
# outputs: now you are in the greet() function

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

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!

装饰器实例:

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 wrapTheFunctiondef a_function():print("I am the function which needs some decoration to remove my foul smell")a_function()
# outputs: "I am the function which needs some decoration to remove my foul smell"a_function =a_new_decorator(a_functionn)
# now a_function is wrapped by wrapTheFunction()a_function()
# 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()

语法糖@:

@a_new_decorator
def a_function():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function()
# 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=  a_new_decorator(a_function)

重构的问题:函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)

print(a_function.__name__)
# Output: wrapTheFunction

functools.wraps的引入:

from functools import wrapsdef 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():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")print(a_function.__name__)
# Output: a_function

综上所述:装饰器本质上是通过程序内容上的一系列操作,把某一个函数的函数体进行了重写,只是名称还是当初那个函数名称,对于计算机来说,只要函数名称一样就会执行相应的函数.

这篇关于python-装饰器骗局的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/876596

相关文章

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.