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 decorator

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

Share

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

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!

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