Table of Contents
回复内容:
Home Backend Development Python Tutorial 什么时候会用到python装饰器?

什么时候会用到python装饰器?

Jun 06, 2016 pm 04:22 PM

回复内容:

这有一份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>
Copy after login
分享一篇我的笔记:Python装饰器笔记(知乎这里排版我排的不好,有意仔细看的可以点前面的链接跳转到简书)
============

一.函数装饰器
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>
Copy after login
再你想改变一个已有函数的功能的时候可以用。 可以添加功能在调用函数之前和之后,这样就可以生成一个基于之前函数的新函数

例如:
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))
Copy after login
偷懒的时候。

装饰器很容易在某个流程中注入一些代码(类似aop),可以集中控制原有函数或者类的行为,可以方便的做全局单例,异常处理等。 说其中一个吧
@classmethod
修饰类成员函数,修饰后类似C++的类全局函数,可以不实例化对象就可调用。
装饰器是在Python 2.4中加入的,它使得函数和方法封装(接收一个函数并返回增强版本的一个函数)更容易阅读和理解。原始的使用场景是可以将方法在定义的首部将其定义为类的方法或静态方法。
常见的装饰器模式包括:
  • 参数检查;
  • 缓存;
  • 代理;
  • 上下文提供者。

Python高级编程 (豆瓣) P37-46
如果你不想看英文文档的话,可以看看这本书。 举个实际的例子:PyQt中绑定事件和事件处理程序的时候
@QtCore.pyqtSlot()
def on_btnOpen_clicked(self):
pass
这样就不用显示的connect了 看一下flask框架。装饰器用的飞起。特别是请求路由。 就像作战里的辅助军一样。正规军干活,辅助军搞点边角料工作。跟你程序逻辑相关部分的放在正规军函数里。而有些辅助逻辑跟主要逻辑无关,又具有很高的重复性,放在主要函数里面会觉得不清晰。做成装饰器,用起来美观大方,符合python的美学。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

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 by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

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 in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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 without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

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...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

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)...

See all articles