Table of Contents
1. Essential
2. The demand is coming
3、问答时间
4、functools.wraps
Home Backend Development Python Tutorial Understanding python decorators

Understanding python decorators

Apr 16, 2018 am 11:53 AM
python Decorator

The content of this article is about the understanding of python decorators. It has a certain reference value. Now I share it with you. Friends in need can refer to it

1. Essential

Core: Functions are "variables"
Definition: The essence is a function, which is to add additional functions to other functions
Principle:
1. Do not modify the source code of the original function

2. Do not modify the calling method of the original function

Higher-order function nested function=>Decorator

#### 第一波 ####
def foo():
    print 'foo'
 
foo     #表示是函数
foo()   #表示执行foo函数
 
#### 第二波 ####
def foo():
    print 'foo'
 
foo = lambda x: x + 1
 
foo()   # 执行下面的lambda表达式,而不再是原来的foo函数,因为函数 foo 被重新定义了
Copy after login

2. The demand is coming

The start-up company has N business departments and 1 basic platform department. The basic platform is responsible for providing underlying functions, such as: Database operations, redis calls, monitoring API and other functions. When business departments use basic functions, they only need to call the functions provided by the basic platform. As follows:

############### 基础平台提供的功能如下 ###############
 
def f1():
    print 'f1'
 
def f2():
    print 'f2'
 
def f3():
    print 'f3'
 
def f4():
    print 'f4'
 
############### 业务部门A 调用基础平台提供的功能 ###############
 
f1()
f2()
f3()
f4()
 
############### 业务部门B 调用基础平台提供的功能 ###############
 
f1()
f2()
f3()
f4()
Copy after login


The company is currently proceeding in an orderly manner. However, in the past, developers of the basic platform did not pay attention to verification-related issues when writing code, namely: the provision of the basic platform The functionality can be used by anyone. Now it is necessary to reconstruct all functions of the basic platform and add a verification mechanism for all functions provided by the platform, that is, verify before executing the function.

The boss gave the job to Low B. Here is what he did:


1


Negotiate with each business department. Each business department writes its own code and verifies it before calling the functions of the basic platform. Hey, this way the basic platform doesn’t need to be modified at all.


Low B was fired that day...

The boss gives the job to Low BB, here’s what he does:


1


Only refactor the code of the basic platform, so that the N business department does not need to make any modifications

############### 基础平台提供的功能如下 ############### def f1():    # 验证1
    # 验证2
    # 验证3
    print 'f1'def f2():    # 验证1
    # 验证2
    # 验证3
    print 'f2'def f3():    # 验证1
    # 验证2
    # 验证3
    print 'f3'def f4():    # 验证1
    # 验证2
    # 验证3
    print 'f4'############### 业务部门不变 ############### ### 业务部门A 调用基础平台提供的功能### f1()
f2()
f3()
f4()### 业务部门B 调用基础平台提供的功能 ### f1()
f2()
f3()
f4()
Copy after login

过了一周 Low BB 被开除了...

老大把工作交给 Low BBB,他是这么做的:

1


只对基础平台的代码进行重构,其他业务部门无需做任何修改

############### 基础平台提供的功能如下 ############### def check_login():    # 验证1
    # 验证2
    # 验证3
    passdef f1():
    
    check_login()    print 'f1'def f2():
    
    check_login()    print 'f2'def f3():
    
    check_login()    print 'f3'def f4():
    
    check_login()    
    print 'f4'
Copy after login

老大看了下Low BBB 的实现,嘴角漏出了一丝的欣慰的笑,语重心长的跟Low BBB聊了个天:

老大说:

写代码要遵循开发封闭原则,虽然在这个原则是用的面向对象开发,但是也适用于函数式编程,简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:

  • 封闭:已实现的功能代码块

  • 开放:对扩展开发

如果将开放封闭原则应用在上述需求中,那么就不允许在函数 f1 、f2、f3、f4的内部进行修改代码,老板就给了Low BBB一个实现方案:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        return func()
    return inner
 
@w1
def f1():
    print 'f1'
@w1
def f2():
    print 'f2'
@w1
def f3():
    print 'f3'
@w1
def f4():
    print 'f4'
Copy after login

对于上述代码,也是仅仅对基础平台的代码进行修改,就可以实现在其他人调用函数 f1 f2 f3 f4 之前都进行【验证】操作,并且其他业务部门无需做任何操作。

Low BBB心惊胆战的问了下,这段代码的内部执行原理是什么呢?

老大正要生气,突然Low BBB的手机掉到地上,恰恰屏保就是Low BBB的女友照片,老大一看一紧一抖,喜笑颜开,交定了Low BBB这个朋友。详细的开始讲解了:

单独以f1为例:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        return func()
    return inner
 
@w1
def f1():
    print 'f1'
Copy after login

当写完这段代码后(函数未被执行、未被执行、未被执行),python解释器就会从上到下解释代码,步骤如下:

  1. def w1(func): ==>将w1函数加载到内存

  2. @w1

没错,从表面上看解释器仅仅会解释这两句代码,因为函数在没有被调用之前其内部代码不会被执行。

从表面上看解释器着实会执行这两句,但是 @w1 这一句代码里却有大文章,@函数名 是python的一种语法糖。

如上例@w1内部会执行一下操作:

  • 执行w1函数,并将 @w1 下面的 函数 作为w1函数的参数,即:@w1 等价于 w1(f1)
    所以,内部就会去执行:
    def inner:
    #验证
    return f1() # func是参数,此时 func 等于 f1
    return inner # 返回的 inner,inner代表的是函数,非执行函数
    其实就是将原来的 f1 函数塞进另外一个函数中

  • 将执行完的 w1 函数返回值赋值给@w1下面的函数的函数名
    w1函数的返回值是:
    def inner:
    #验证
    return 原来f1() # 此处的 f1 表示原来的f1函数
    然后,将此返回值再重新赋值给 f1,即:
    新f1 = def inner:
    #验证
    return 原来f1()
    所以,以后业务部门想要执行 f1 函数时,就会执行 新f1 函数,在 新f1 函数内部先执行验证,再执行原来的f1函数,然后将 原来f1 函数的返回值 返回给了业务调用者。
    如此一来, 即执行了验证的功能,又执行了原来f1函数的内容,并将原f1函数返回值 返回给业务调用着

Low BBB 你明白了吗?要是没明白的话,我晚上去你家帮你解决吧!!!

先把上述流程看懂,之后还会继续更新...

3、问答时间

问题:被装饰的函数如果有参数呢?

def w1(func):    def inner(arg):        # 验证1
        # 验证2
        # 验证3
        return func(arg)    return inner

@w1def f1(arg):    print 'f1'
Copy after login


def w1(func):    def inner(arg1,arg2):        # 验证1
        # 验证2
        # 验证3
        return func(arg1,arg2)    return inner

@w1def f1(arg1,arg2):    print 'f1'
Copy after login


def w1(func):    def inner(arg1,arg2,arg3):        # 验证1
        # 验证2
        # 验证3
        return func(arg1,arg2,arg3)    return inner

@w1def f1(arg1,arg2,arg3):    print 'f1'
Copy after login

问题:可以装饰具有处理n个参数的函数的装饰器?

def w1(func):
    def inner(*args,**kwargs):
        # 验证1
        # 验证2
        # 验证3
        return func(*args,**kwargs)
    return inner
 
@w1
def f1(arg1,arg2,arg3):
    print 'f1'
Copy after login

问题:一个函数可以被多个装饰器装饰吗?

def w1(func):
    def inner(*args,**kwargs):
        # 验证1
        # 验证2
        # 验证3
        return func(*args,**kwargs)
    return inner
 
def w2(func):
    def inner(*args,**kwargs):
        # 验证1
        # 验证2
        # 验证3
        return func(*args,**kwargs)
    return inner
 
 
@w1
@w2
def f1(arg1,arg2,arg3):
    print 'f1'
Copy after login

问题:还有什么更吊的装饰器吗?

#!/usr/bin/env python
#coding:utf-8
  
def Before(request,kargs):
    print 'before'
      
def After(request,kargs):
    print 'after'
  
  
def Filter(before_func,after_func):
    def outer(main_func):
        def wrapper(request,kargs):
              
            before_result = before_func(request,kargs)
            if(before_result != None):
                return before_result;
              
            main_result = main_func(request,kargs)
            if(main_result != None):
                return main_result;
              
            after_result = after_func(request,kargs)
            if(after_result != None):
                return after_result;
              
        return wrapper
    return outer
      
@Filter(Before, After)
def Index(request,kargs):
    print 'index'
Copy after login

4、functools.wraps

上述的装饰器虽然已经完成了其应有的功能,即:装饰器内的函数代指了原函数,注意其只是代指而非相等,原函数的元信息没有被赋值到装饰器函数内部。例如:函数的注释信息

def outer(func):    def inner(*args, **kwargs):        print(inner.__doc__)  # None
        return func()    return inner

@outerdef function():    """
    asdfasd
    :return:    """
    print('func')
Copy after login


如果使用@functools.wraps装饰装饰器内的函数,那么就会代指元信息和函数。


def outer(func):
    @functools.wraps(func)    def inner(*args, **kwargs):        print(inner.__doc__)  # None
        return func()    return inner

@outerdef function():    """
    asdfasd
    :return:    """
    print('func')
Copy after login

The above is the detailed content of Understanding python decorators. For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles