什么时候会用到python装饰器?
回复内容:
这有一份Python官方的装饰器实例列表,你可以在里边看到装饰器的各种妙用:PythonDecoratorLibrary,基本上你差不多能想到的都有了。差不多有这么几类:
1. 注入参数(提供默认参数,生成参数)
2. 记录函数行为(日志、缓存、计时什么的)
3. 预处理/后处理(配置上下文什么的)
4. 修改调用时的上下文(线程异步或者并行,类方法)
装饰器其实也就是一个函数,一个用来包装函数的函数,返回一个修改之后的函数对象。经常被用于有切面需求的场景,较为经典的有插入日志、 性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装 饰器的作用就是为已经存在的对象添加额外的功能。
首先来看看一个小例子:
<span class="k">def</span> <span class="nf">alan</span><span class="p">():</span> <span class="k">print</span><span class="p">(</span><span class="s">'alan speaking'</span><span class="p">)</span>
============
一.函数装饰器
1.从Python内层函数说起
首先我们来探讨一下这篇文章所讲的内容Inner Functions - What Are They Good For?(中文版)
使用内层函数的三个好处- 封装
- 贯彻DRY原则
- 闭包和工厂函数
1.封装
<span class="k">def</span> <span class="nf">outer</span><span class="p">(</span><span class="n">num1</span><span class="p">):</span> <span class="k">def</span> <span class="nf">inner_increment</span><span class="p">(</span><span class="n">num1</span><span class="p">):</span> <span class="c"># hidden from outer code</span> <span class="k">return</span> <span class="n">num1</span> <span class="o">+</span> <span class="mi">1</span> <span class="n">num2</span> <span class="o">=</span> <span class="n">inner_increment</span><span class="p">(</span><span class="n">num1</span><span class="p">)</span> <span class="k">print</span><span class="p">(</span><span class="n">num1</span><span class="p">,</span> <span class="n">num2</span><span class="p">)</span> <span class="n">inner_increment</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="err">#不能正确运行</span> <span class="c"># outer(10) #可以正常运行</span>
例如:
def addOne(func): def wraper(*args,**kwargs): saySmthing = "Result :" return saySmthing +" "+ str(func(*args,**kwargs)) return wraper @addOne def func(a,b): return a+b print(func(10,20))
装饰器很容易在某个流程中注入一些代码(类似aop),可以集中控制原有函数或者类的行为,可以方便的做全局单例,异常处理等。 说其中一个吧
@classmethod
修饰类成员函数,修饰后类似C++的类全局函数,可以不实例化对象就可调用。
装饰器是在Python 2.4中加入的,它使得函数和方法封装(接收一个函数并返回增强版本的一个函数)更容易阅读和理解。原始的使用场景是可以将方法在定义的首部将其定义为类的方法或静态方法。
常见的装饰器模式包括:
- 参数检查;
- 缓存;
- 代理;
- 上下文提供者。
Python高级编程 (豆瓣) P37-46
如果你不想看英文文档的话,可以看看这本书。 举个实际的例子:PyQt中绑定事件和事件处理程序的时候
@QtCore.pyqtSlot()
def on_btnOpen_clicked(self):
pass
这样就不用显示的connect了 看一下flask框架。装饰器用的飞起。特别是请求路由。 就像作战里的辅助军一样。正规军干活,辅助军搞点边角料工作。跟你程序逻辑相关部分的放在正规军函数里。而有些辅助逻辑跟主要逻辑无关,又具有很高的重复性,放在主要函数里面会觉得不清晰。做成装饰器,用起来美观大方,符合python的美学。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
