Python 装饰器学习记录
2021/7/22 9:36:42
本文主要是介绍Python 装饰器学习记录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
基础教程:
https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。
装饰器让你在一个函数的前后去执行代码
装饰器模型
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()
向decorator传入参数
decorator必须仅接受一个被修饰的函数为参数,这也是为什么我们必须再外包裹一层从而接受那些额外的参数并且产生我们的decorator的原因。这个例子中tags函数是我们的decorator generator
def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): return "Hello "+name print get_text("John") # Outputs <p>Hello John</p>
目标:用装饰器写多次尝试连接
这篇关于Python 装饰器学习记录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程