Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use python closures and decorators

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "python closures and decorators", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "python closures and decorators how to use" article.

I. closure

Conditions for the formation of closures:

1. Function nesting.

two。 The internal function uses the variables or parameters of the external function.

3. The external function returns the internal function that uses the outer variable.

A simple example def func_out (num1): def inner (num2): res = num1 + num2 print (res) return inner# a = func_out (10) (10) a = func_out (10) a (10)

Closures modify variables of external functions:

You need to use the nonlocal keyword to modify the variables of an external function within a closure

Def func_out (): # variable of external function num1 = 10 def func_inner (): # modify variable of external function nonlocal num1 num1 = 20 res = num1 + 20 print (res) print ("variable before modification", num1) func_inner () print ("modified variable") Num1) return func_innernew_func = func_out () new_func () III. Decorator 3.1 simple decorator

A decorator is a function that adds extra functionality to an existing function, which is essentially a closure function, that is to say, a function nesting. Functional features of the decorator:

1. Do not modify the source code of existing functions

two。 Do not modify the way existing functions are called

3. Add additional functions to existing functions

When users make comments, they need to verify whether the user is logged in. We will first want to modify the original function and add some functions to the function, but in this era of division and cooperation, such modifications are likely to cause problems with the function after modifying the ancestral code, and also affect the efficient reuse of the code. In order not to modify the original comments of the code, to achieve a high level of code reuse.

The original function and its calls:

Def comment (): print ("execute ancestral code.") Print ("comment") # call comment function comment ()

Write a function that implements the function of the decorator to implement login verification:

Def decorator (func): def inner (): print ('verifying login identity... Verify successful') func () return innerdef comment (): print ("execute ancestral code.") Print ("comment") # call comment function comment = decorator (comment) comment ()

Enter the result:

Verifying the identity of the logger...

Verify successfully

Execute ancestral code...

Comment

3.1.1 grammatical sugar using decorators

The grammar of the decorator is written in sugar: @ decorator name

For example, it can be rewritten as follows:

Def decorator (func): def inner (): print ('verifying login identity... Verify successful') func () return inner@decoratordef comment (): print ("execute ancestral code.") Print ("comment") # call the function comment ()

Running result:

Verifying the identity of the logger...

Verify successfully

Execute ancestral code...

Comment

3.1.2 timing of execution of decorator

The conclusion first: when using the decorator syntax sugar, the decorator function will be executed first.

Def decorator (func): # timing of test decorator execution print ('--remark1----') def inner (): print ('verifying login identity. Verification successful') func () print ('- remark2---') return inner@decoratordef comment (): print ("execute ancestral code.") Print ("comment")

Output result:

-remark1

-remark2-

3.2 Universal decorator

Decorated functions may have arguments passed, or return values. In the above example, if you still use the above method and retrograde decorator decoration will be a problem, is there a general-purpose decorator that can decorate any function?

3.2.1 decorate the function def logging (fn): def inner (num1,num2): print ('performed a calculation') fn (num1,num2) return inner# using the decorator decorator function @ loggingdef sum_num (result b): result = a + b print (result) sum_num (1Jue 2) 3.2.2. Decorate the function with a return value: def logging (fn): def inner (num1,num2): print ('performed a calculation') result = fn (num1,num2) return result return inner# uses the decorator decorator function @ loggingdef sum_num (afield b): result = a + b return result print (sum_num (1Magazine 2)) 3.2.3 implement a general decorator

* args: used to receive tuple parameters, which can be passed or not

* * kwargs: used to receive dictionary type parameters, which can be passed or not

Def logging (fn): def inner (* args, * * kwargs): result = fn (* args, * * kwargs) return result return inner@loggingdef sum_num (return result return inner@loggingdef sum_num b): result = a + b return result3.3 use of multiple decorators

The process of multiple decorators: from the inside to the outside of the decoration process, first the execution of the internal decorator, and then the execution of the external decorator.

Principle analysis: content = make_div (make_p (content))

Disassemble step by step: content=make_p (content), interior decorator to complete content=make_p.inner, content=make_ div (make_p.inner)

Def make_div (func): print ("make_div decorator executed") def inner (): # decorating existing functions in internal functions result = "" + func () + "" return result return innerdef make_p (func): print ("make_p decorators executed") def inner (): # decorating existing functions in internal functions result = "

"+ func () +"

"return result return inner@make_div@make_pdef content (): return" Life is too short, I use Python.

Output:

The make_p decorator executes

The make_div decorator executes

Life is too short. I use Python.

3.4 decorator with parameters

The timing of the decorator with parameters is to define a function, let the function receive the parameters, and then return the decorator inside the function.

Such as defining a decorator that can judge addition or subtraction:

Def return_decorator (flag): def decorator (func): def inner (aMaginb): if flag = ='+': print ("addition in progress") elif flag = ='-': print ("subtraction") func (a B) return inner return decorator@return_decorator ('+') def add_num (aMagneb): print (axib) add_num (1meme 5) 3.5 class decorators

Decorate existing functions with classes.

Class MyDecorator (object): def _ init__ (self,func): self.__func = func # implements the _ _ call__ method, which makes the object callable, and # callable objects can be used like functions. Def _ _ call__ (self,*args,**kwargs): # Encapsulation of existing parameters print ('--decorating -') self.__func () @ MyDecoratordef show (): print ("hello") # points to MyDecorator class to create instance object-> show () = > object () show ()

Output:

-decorating in progress-

Hello

The above is about the content of this article on "how to use python closures and decorators". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report