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

What is the definition and usage of Python decorator

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the definition and use of Python decorator". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what is the definition and use of Python decorator"!

1. Definition of decorator

Decorator: a function that adds additional functionality to an existing function, which is essentially a closure function

Features:

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

4. Parse the decorator when the code is executed

Import time # principle of decorator # def show (): # nasty decorator for i in range (10000000): # n+=i# print ('show_') N) # define a closure # def count_time (fun): # def inner (): # start=time.time () # fun () # end=time.time () # print (f' {end-start} seconds') # return inner## # how the decorator decorates the function # show=count_time (show) # show () # defines the decorator (language) Sugar) def count_time (fun): # there must be a parameter to receive the decorated function def inner (): start=time.time () fun () end=time.time () print (f'{end-start} seconds') return inner# decorator written: @ closure of the external function Must be interpreted as show=count_time (show) using print ('parse decorator 1') @ count_time # after the closure is fixed Show points to innerdef show () in the count_time function: for i in range (10000000): print ('show_',n) print (' parsing decorator 2') @ count_time # as display=count_time (display) def display (): print ('Display') print (' official execution..') show () display () 2. Definition of general types of decorators

(the same applies when the decorated function has parameters or a return value)

Def outer (func): def inner (* args,**kwargs): # * unpack tuples and lists, * * unpack print ('* * 30) print (args,kwargs) ret=func (* args,**kwargs) # unpack dictionary Otherwise, the formal parameter is a tuple or dictionary print ('* * 30) return ret return inner @ outerdef show (name,msg): return str (name) + 'say:' + str (msg) print (show ('Tom',msg='Hello')) 3. Multiple decorators decorate a function at the same time # first closure def wrapper_div (func): def inner (* args,**kwargs): return'+ func (* args,**kwargs) + 'return inner # second closure def wrapper_p (func): def inner (* args,**kwargs): return'

'+ func (* args,**kwargs) +'

'return inner # decorate from bottom to top, execute @ wrapper_div@wrapper_p# from top to bottom to define a function def show (): return' Short life I use Python.' Print (show ()) #

Short life I use Python.

4. Multiple decorators decorate a function at the same time (2) def outer1 (func): def inner (): print ('decorator 1-1') func () print ('decorator 1-2') return inner def outer2 (func): def inner (): print ('decorator 2-1') func () print ('decorator 2-2') Return inner'''1.show points to outer1.inner2.outer1.inner.func, points to outer2.inner3.outer2.inner.func, points to show'''@outer1@outer2def show (): print ('Show...') Show () 5. Class decorator uses the method import time class Wrapper (): def _ init__ (self,func): self.func=func # when this method is implemented in a class, the instance object of the class becomes a callable object, that is, you can add () def _ call__ (self, * args, * * kwargs): print ('decorative content 1.') after the instance object Start=time.time () ret=self.func (* args,**kwargs) end=time.time () print (f' executed {end-start} seconds') print ('decorative content 2.') Return ret

After the execution of the decorator, the decorated function points to the instance object of the class.

If you let the decorated function execute, then add the _ _ call__ method to the class, which is equivalent to the inner function in the closure format

Once the call is executed by the decorated function, the _ _ call__ function in the instance object is executed

@ Wrapper # is interpreted as show=Wrapper (show), and show becomes an object of the class def show (): print ('Show...') Show () 6. Decorator with parameters (use a decorator with parameters In fact, there is another function wrapped around the decorator) # @ Author: Kant# @ Time: 22:43 on 2022-1-23 def set_args (msg): def outer (func): def inner (): print ('decorative content', msg) func () return inner return outer''using a decorator with parameters, actually wrapping another function around the decorator Using this function to receive parameters returns the address reference that the decorator will return to outer after calling set_args (), which becomes @ outer'''@set_args ('Hello') # No matter what the closure function looks like, the decorated function always points to the inner function def show (): print (' Show...') of the closure function. Show () 6. Using decorator to automatically maintain routing table

Routing function: the address of the resource can be found through the requested path

# define a routing table dictionary router_table= {} def router (url): def wrapper (func): def inner (): print ('1') print ('inner-',func) # to see who the current decorated function is func () # maintain the routing table dictionary router_ table [url] = inner # if you write func Nothing in the inner function executes print ('routing table dictionary:' Router_table) return inner return wrapper @ router ('index.html') def index (): print (' home content') @ router ('center.html') def center (): print (' personal Center') @ router ('mail.html') def mail (): print (' email page') @ router ('login.html') def login (): print (' login page') def error () : print ('access page does not exist') def request_url (url): func=error if url in router_table: func=router_ table [url] func () print ('start executing function') request_url ('index.html') request_url (' center.html') request_url ('mail.html') request_url (' test.html') request_url ('login.html') so far I believe you have a deeper understanding of "what is the definition and use of Python decorator", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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