


Python---detailed explanation of decorators
Definition:
Essentially a function. Its function is to decorate another function (that is, the decorated function) and add functionality to the decorated function. The premise is that the source code and calling method of the decorated function cannot be changed. Such a function is called a decorator.
Analysis:
## Let’s talk about it below Not much to say, just explain it in code. Below is a function.
b=1+2Program output: ————————3————————Now I want to add an explanatory sentence to this function, as follows, we can write a decorator:
1 #原函数 2 def add(): 3 a=1+2 4 print(a) 5 #装饰器 6 def decorator(func): 7 def warpper(): 8 print("1+2的结果是:") 9 func()10 return warpper11 #注意此句 12 add=decorator(add)13 #调用函数14 add()Program output: ——————————The result of 1+2 is: 3——————————
In this way we successfully achieved our goal. Pay attention to this sentence on line 12. This sentence passes the add function object into the decorator() function, and returns a new function variable. This new function object is reassigned to add, so that it can be guaranteed not to change. The calling method of the decorated function remains unchanged. There is a more elegant way to replace the statement on line 12 in Python syntax. As follows:
1 #装饰器 2 def decorator(func): 3 def warpper(): 4 print("1+2的结果是:") 5 func() 6 return warpper 7 8 #add=decorator(add) 9 #原函数10 @decorator#换成@符号11 def add():12 a=1+213 print(a)14 #调用函数15 add()Add "@xxx" directly in front of the decorated function (xxx is the decorator function name)
#What should I do if the decorated function has parameters?
What if the decorated function has parameters? How should we work? Don't worry, we can collect parameters in the form of indefinite parameters. The example code is as follows:1 def decorator(func): 2 def warpper(*args,**kwargs): 3 print("相加的结果是:") 4 func(*args,**kwargs) 5 return warpper 6 7 @decorator 8 def add(x,y): 9 a=x+y10 print(a)11 12 add(2,3)
程序输出: —————————————————— 相加的结果是: 5 ——————————————————
1 def index():2 print("welcome to the index page")3 def home():4 print("welcome to the home page")5 def bbs():6 print("welcome to the bbs page")7 return "I am the return contents"If we now want to add verification to the home page and bbs page, obviously it is not feasible to change the source code now. At this time we can use the decorator, as follows:
1 username,passwd="jack","abc123"#模拟一个已登录用户 2 def decorator(func): 3 def warpper(*args,**kwargs): 4 Username=input("Username:").strip() 5 password=input("Password:").strip() 6 if username==Username and passwd==password: 7 print("Authenticate Success!") 8 func(*args,**kwargs) 9 else:10 exit("Username or password is invalid!")11 return warpper12 13 def index():14 print("welcome to the index page")15 @decorator16 def home():17 print("welcome to the home page")18 @decorator19 def bbs():20 print("welcome to the bbs page")21 return "I am the return contents"22 23 index()24 home()25 bbs()Program result: ————————welcome to the index page #You can log in directly to the index page without verification
Username:jack
Password:abc123
Authenticate Success! :jack
————————
We noticed that bbs() has a return value. If we change the last sentence of the above code (line 25) to “print(bbs() )" and then look at his output:
————————
Username:jack
Password:abc123Authenticate Success!
welcome to the home pageUsername:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
None Has it become None? ? ?
————————
What happened! The return value of bbs() is printed as None. how so? Wouldn't this change the source code of the decorated function? How can this be solved? Let’s analyze it:
When we execute the bbs function, it is actually equivalent to executing the wrapper function in the decorator. After careful analysis of the decorator, we found that the wrapper function has no return value, so in order to let it To ensure that the return value of the decorated function can be returned correctly, the decorator needs to be modified:
1 username,passwd="jack","abc123"#模拟一个已登录用户 2 def decorator(func): 3 def warpper(*args,**kwargs): 4 Username=input("Username:").strip() 5 password=input("Password:").strip() 6 if username==Username and passwd==password: 7 print("Authenticate Success!") 8 return func(*args,**kwargs)#在这里加一个return就行了 9 else:10 exit("Username or password is invalid!")11 return warpper12 13 def index():14 print("welcome to the index page")15 @decorator16 def home():17 print("welcome to the home page")18 @decorator19 def bbs():20 print("welcome to the bbs page")21 return "I am the return contents"22 23 index()24 home()25 bbs()
如图加上第8行的return就可以解决了。下面我们在看看改后的程序输出:
————————
welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
I am the return contents #bbs()的返回值得到了正确的返回
——-——————
好了,返回值的问题解决了.
既然装饰器是一个函数,那装饰器可以有参数吗?
答案是肯定的。我们同样可以给装饰器加上参数。比如还是上面的三个页面函数作为例子,我们可以根据不同页面的验证方式来给程序不同的验证,而这个验证方式可以以装饰器的参数传入,这样我们就得在装饰器上在嵌套一层函数 了:
1 username,passwd="jack","abc123"#模拟一个已登录用户 2 def decorator(auth_type): 3 def out_warpper(func): 4 def warpper(*args,**kwargs): 5 Username=input("Username:").strip() 6 password=input("Password:").strip() 7 if auth_type=="local": 8 if username==Username and passwd==password: 9 print("Authenticate Success!")10 return func(*args,**kwargs)11 else:12 exit("Username or password is invalid!")13 elif auth_type=="unlocal":14 print("HERE IS UNLOCAL AUTHENTICATE WAYS")15 return warpper16 return out_warpper17 18 def index():19 print("welcome to the index page")20 @decorator(auth_type="local")21 def home():22 print("welcome to the home page")23 @decorator(auth_type="unlocal")24 def bbs():25 print("welcome to the bbs page")26 return "I am the return contents"27 28 index()29 home()30 bbs()
输出:
————————
welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
HERE IS UNLOCAL AUTHENTICATE WAYS
————————
可见,程序分别加入了第2行和第16行和中间的根据auth_type参数的判断的相关内容后, 就解决上述问题了。对于上面的这一个三层嵌套的相关逻辑,大家可以在 pycharm里头加上断点,逐步调试,便可发现其中的道理。
总结
要想学好迭代器就必须理解一下三条:
1.函数即变量(即函数对象的概念)
2.函数嵌套
3.函数式编程
The above is the detailed content of What does python decorator mean? How to use python decorators?. For more information, please follow other related articles on the PHP Chinese website!

C++中的众数函数详解在统计学中,众数指的是一组数据中出现次数最多的数值。在C++语言中,我们可以通过编写一个众数函数来找到任意一组数据中的众数。众数函数的实现可以采用多种不同的方法,下面将详细介绍其中两种常用的方法。第一种方法是使用哈希表来统计每个数字出现的次数。首先,我们需要定义一个哈希表,将每个数字作为键,出现次数作为值。然后,对于给定的数据集,我们遍

C++中的取余函数详解在C++中,取余运算符(%)用于计算两个数相除的余数。它是一种二元运算符,其操作数可以是任何整数类型(包括char、short、int、long等),也可以是浮点数类型(如float、double)。取余运算符返回的结果与被除数的符号相同。例如,对于整数的取余运算,我们可以使用以下代码来实现:inta=10;intb=3;

Vue.nextTick函数用法详解及在异步更新中的应用在Vue开发中,经常会遇到需要进行异步更新数据的情况,比如在修改DOM后需要立即更新数据或者在数据更新后需要立即进行相关操作。而Vue提供的.nextTick函数就是为了解决这类问题而出现的。本文就会详细介绍Vue.nextTick函数的用法,并结合代码示例来说明它在异步更新中的应用。一、Vue.nex

PHP-FPM是一种常用的PHP进程管理器,用于提供更好的PHP性能和稳定性。然而,在高负载环境下,PHP-FPM的默认配置可能无法满足需求,因此我们需要对其进行调优。本文将详细介绍PHP-FPM的调优方法,并给出一些代码示例。一、增加进程数默认情况下,PHP-FPM只启动少量的进程来处理请求。在高负载环境下,我们可以通过增加进程数来提高PHP-FPM的并发

在Web应用程序中,缓存通常是用来优化性能的重要手段。Django作为一款著名的Web框架,自然也提供了完善的缓存机制来帮助开发者进一步提高应用程序的性能。本文将对Django框架中的缓存机制进行详解,包括缓存的使用场景、建议的缓存策略、缓存的实现方式和使用方法等方面。希望对Django开发者或对缓存机制感兴趣的读者有所帮助。一、缓存的使用场景缓存的使用场景

在PHP开发中,有时我们需要判断某个函数是否可用,这时我们便可以使用function_exists()函数。本文将详细介绍function_exists()函数的用法。一、什么是function_exists()函数?function_exists()函数是PHP自带的一个内置函数,用于判断某个函数是否被定义。该函数返回一个布尔值,如果函数存在返回True,

PHPstrpos()函数用法详解在PHP编程中,字符串处理是非常重要的一部分。PHP通过提供一些内置函数来实现字符串处理。其中,strpos()函数就是PHP中最常用的一个字符串函数之一。该函数的目的是在一个指定的字符串中搜索另一个指定字符串的位置,如果包含则返回这个位置,否则返回false。本文将通过详细分析PHPstrpos()函数的用法,助你更好

Gin框架是目前非常流行的Go语言Web框架之一。作为一个轻量级的框架,Gin提供了丰富的功能和灵活的架构,使得它在Web开发领域中备受欢迎。其中一个特别重要的功能是模板渲染。在本文中,我们将介绍Gin框架的模板渲染功能,并深入了解它的实现原理。一、Gin框架的模板渲染功能Gin框架使用了多种模板渲染引擎来构建Web应用程序。目前,它支持以下几种模板引擎:


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

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