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

相关文章

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.

Python轻松实现Word到Markdown的转换

《Python轻松实现Word到Markdown的转换》在文档管理、内容发布等场景中,将Word转换为Markdown格式是常见需求,本文将介绍如何使用FreeSpire.DocforPython实现... 目录一、工具简介二、核心转换实现1. 基础单文件转换2. 批量转换Word文件三、工具特性分析优点局

Python中4大日志记录库比较的终极PK

《Python中4大日志记录库比较的终极PK》日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程,:本文主要介绍Python中4大日志记录库比较的相关资料,文中通过代码介绍的非常详细,... 目录一、logging库1、优点2、缺点二、LogAid库三、Loguru库四、Structlogphp

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

Python海象运算符:=的具体实现

《Python海象运算符:=的具体实现》海象运算符又称​​赋值表达式,Python3.8后可用,其核心设计是在表达式内部完成变量赋值并返回该值,从而简化代码逻辑,下面就来详细的介绍一下如何使用,感兴趣... 目录简介​​条件判断优化循环控制简化​推导式高效计算​正则匹配与数据提取​性能对比简介海象运算符

python项目环境切换的几种实现方式

《python项目环境切换的几种实现方式》本文主要介绍了python项目环境切换的几种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 如何在不同python项目中,安装不同的依赖2. 如何切换到不同项目的工作空间3.创建项目

python项目打包成docker容器镜像的两种方法实现

《python项目打包成docker容器镜像的两种方法实现》本文介绍两种将Python项目打包为Docker镜像的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录简单版:(一次成功,后续下载对应的软件依赖)第一步:肯定是构建dockerfile,如下:第二步

Python + Streamlit项目部署方案超详细教程(非Docker版)

《Python+Streamlit项目部署方案超详细教程(非Docker版)》Streamlit是一款强大的Python框架,专为机器学习及数据可视化打造,:本文主要介绍Python+St... 目录一、针对 Alibaba Cloud linux/Centos 系统的完整部署方案1. 服务器基础配置(阿里