当前位置: 首页 > news >正文

Python 开发 - Python 装饰器(装饰器概述、函数概念、装饰器手动实现、装饰器语法糖实现)

一、装饰器概述

  1. 装饰器允许开发者在不修改原函数代码的情况下,给函数添加额外的功能

  2. 装饰器本质上是一个返回函数的高阶函数

  3. 在 Python 中,使用装饰器语法糖@可以便捷应用装饰器


二、函数概念

1、函数是一等对象
  1. 函数可以赋值给变量
defgreet(name):returnf"Hello,{name}"my_func=greetprint(my_func("Alice"))
# 输出结果 Hello, Alice
  1. 函数可以作为参数传递
defgreet(name):print(f"Hello,{name}")defcall_twice(func,arg):greet(arg)greet(arg)call_twice(greet,"Alice")
# 输出结果 Hello, Alice Hello, Alice
  1. 可以定义在另一个函数内部
defcall_twice(arg):defgreet(name):returnf"Hello,{name}"print(greet(arg)+" "+greet(arg))call_twice("Alice")
# 输出结果 Hello, Alice Hello, Alice
  1. 函数可以作为返回值
defget_func(flag):defadd(num1,num2):returnnum1+num2defsubtract(num1,num2):returnnum1-num2ifflag=="+":returnaddelifflag=="-":returnsubtract result_func=get_func("+")result=result_func(10,20)print(result)
# 输出结果 30
2、闭包
  • 闭包是嵌套函数中,内部函数引用外部函数的变量,即使外部函数已经执行完毕

  • 如下例,函数 inner_func 引用了外部函数的变量 x,即使函数 outer_func 已经执行完,函数 closure 仍能访问 x

defouter_func(x):definner_func(y):returnx+yreturninner_func closure=outer_func(10)result=closure(5)print(result)
# 输出结果 15

三、装饰器手动实现

  1. 基本实现
# 装饰器函数defmy_decorator(func):defwrapper():print("函数执行前")result=func()print("函数执行后")returnresultreturnwrapper# 原始函数defsay_hello():print("Hello")# 应用装饰器decorated_say_hello=my_decorator(say_hello)decorated_say_hello()
# 输出结果 函数执行前 Hello 函数执行后
  1. 函数带参数
# 装饰器函数defmy_decorator(func):defwrapper(**kwargs):print("函数执行前")result=func(**kwargs)print("函数执行后")returnresultreturnwrapper# 原始函数defsay_hello(name):print(f"Hello,{name}")# 应用装饰器decorated_say_hello=my_decorator(say_hello)decorated_say_hello(name="Alice")
# 输出结果 函数执行前 Hello, Alice 函数执行后
  1. 装饰器带参数
# 装饰器函数defmy_decorator(func,times):defwrapper():print("函数执行前")foriinrange(times):func()print("函数执行后")returnwrapper# 原始函数defsay_hello():print("Hello World")# 应用装饰器decorated_say_hello=my_decorator(say_hello,3)decorated_say_hello()
# 输出结果 函数执行前 Hello World Hello World Hello World 函数执行后

四、装饰器语法糖实现

  1. 基本实现
# 装饰器函数defmy_decorator(func):defwrapper():print("函数执行前")result=func()print("函数执行后")returnresultreturnwrapper# 应用装饰器@my_decoratordefsay_hello():print("Hello")say_hello()
# 输出结果 函数执行前 Hello 函数执行后
  1. 函数带参数
# 装饰器函数defmy_decorator(func):defwrapper(**kwargs):print("函数执行前")result=func(**kwargs)print("函数执行后")returnresultreturnwrapper# 应用装饰器@my_decoratordefsay_hello(name):print(f"Hello,{name}")say_hello(name="Alice")
# 输出结果 函数执行前 Hello, Alice 函数执行后
  1. 装饰器带参数
# 装饰器函数defmy_decorator(times):defdecorator(func):defwrapper():print("函数执行前")foriinrange(times):func()print("函数执行后")returnwrapperreturndecorator# 应用装饰器@my_decorator(times=3)defsay_hello():print("Hello World")say_hello()
# 输出结果 函数执行前 Hello World Hello World Hello World 函数执行后
http://www.cnnetsun.cn/news/81755.html

相关文章:

  • 太阳能电池串IV检测系统:精准契合行业标准,筑牢光伏质量防线
  • 64、Ubuntu 下 C/C++ 编程与 Mono 开发全解析
  • 5、Ubuntu系统网络与图形界面使用指南
  • 快速构建MCP工具的开发包FastMCP
  • 推荐字节的文档图像解析工具Dolphin
  • 查 Intel CPU 信息不用绕弯!这个专属查询工具,精准直达官网详情~
  • MediaCreationTool 报错?用 Rufus 一键制作 Windows 启动 U 盘,兼容 Win10/11!
  • Dify平台提示词调试功能提升AI输出质量实测
  • Java JDK下载+安装+配置环境(详细教程含图片),小白收藏这篇就够了
  • 前端性能优化之大文件上传,零基础入门到精通,收藏这篇就够了
  • 37、Windows 8 安全与诊断实用指南
  • 蛋白质丙酰化修饰在代谢调控与疾病研究中的进展与应用
  • C# + LiveCharts 工业监控界面,实时数据可视化实战
  • 在数字中国建设大潮中,科技管理部门如何借助靶向的知识产权智能运营平台解决客户流失率高,达成重塑差异化服务优势,最终重塑健全长效运营机制?
  • 如何确保服务器的安全性
  • 获取JD商品详情数据 get_item_pro
  • 提权学习之旅—Windows操作系统如何提升权限,网络安全零基础入门到精通实战教程!
  • Directus:重新定义企业数据管理的开源革命
  • RAX3000M刷机终极指南:从零开始玩转OpenWrt系统
  • 软件产品设计中用户体验提升的主要问题分析
  • Typst数学排版终极指南:告别对齐困扰,打造完美公式
  • 22、企业环境下迁移 Windows 应用到 Linux 及瘦客户端计算的全面解析
  • 24、探索瘦客户端计算与Linux桌面资源
  • IT66122FN-300:低功耗发射器,配备HDMI 1.4 3D
  • uniapp+springboot微信小程序民宿预订管理系统设计与实现_337b01q6_论文
  • 第135篇:美国APT的苹果手机“三角测量“行动是如何被溯源发现的
  • 高效节能的工业动力核心:西门子罗宾康高压变频器LDZ14501000.070
  • CosyVoice语音合成实战指南:从零到一掌握微调全流程
  • 使用 Coze MCP 插件 + curl 调用工具生成高质量提示词示例
  • 5个Apache Weex渲染性能提升技巧:终极优化指南