How to use Python decorator
This article is about how to use the Python decorator. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Basic use of the decorator (decorated with arguments) def decorator (func): def inner (info): print ('inner') func (info) return inner@decoratordef show_info (info): print (info) show_info (' hello') prevent the decorator from changing the name of the decorating function
When decorating the function, the decorator returns the function address of inner, so the name of the function will be changed and show_info.__name__ will become inner. To prevent this phenomenon, you can use functools.
Import functoolsdef decorator (func): @ functools.wraps (func) def inner (info): print ('inner') func (info) return inner@decoratordef show_info (info): print (info) show_info (' hello')
Writing in this way will not change the name of the decorated function
Decorator dynamic registration function
This method is reflected in the source code of app.Route () of the Flask framework
Class Commands (object): def _ init__ (self): self.cmd = {} def regist_cmd (self, name: str)-> None: def decorator (func): self.cmd [name] = func print ('func:' Func) return func return decoratorcommands = Commands () # so that the value of S1 points to the function address of show_h @ commands.regist_cmd ('S1') def show_h (): print ('show_h') # so that the value of S2 points to the function address of show_e @ commands.regist_cmd (' S2') def show_e (): print ('show_e') func = commands.cmd [' s1'] func () personal experience
You can use func_name when reading the decorator code
As an example
@ commands.regist_cmd ('s2') def show_e (): print (' show_e')
That is, show_e = commands.regist_cmd ('s2') (show_e)
Thank you for reading! This is the end of this article on "how to use Python decorator". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!