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

Example analysis of python decorator code

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the python decorator code example analysis, the article introduces in great detail, has a certain reference value, interested friends must read it!

1. Def wrapper (fn): def inner (* args, * * kwargs): ret = fn (* args, * * kwargs) return ret return inner

There are several key points for the decorator:

1. Function can be passed as an argument

two。 Function can be returned as a return value

3. Function names can be assigned as variables

The decorator is essentially a closure, adding new functions to the function without changing the original function call.

For example:

Def admin (game): def inner (* args, * * kwargs): # inner adds a parameter, args must be a tuple kwargs must be a dictionary print ('open Wg') result = game (* args, * * kwargs) # * means to break args tuple and kwargs into position parameters, and the keyword parameter is passed into print (' close Wg') return result return inner@admindef play_dnf (username) Password): print (f' starts to play DNF, account: {username}, password: {password}') print ('cut the body, heart cut the soul') return 'drop: kill the wailing cannon' @ admindef play_wow (race, occupation, server_name, camp): print (f' start playing World of Warcraft, race: {race}, class: {occupation}, server: {server_name} Camp: {camp}') print ('for the glory of Sindolay') return 'fall: Ashbringer' if _ _ name__ = ='_ _ main__': ret1 = play_dnf ('Horse Monkey', '888888') print (ret1) ret2 = play_wow ('Blood Elf', 'Paladin', 'Echo Hill', 'Tribe') print (ret2)

The code is easy to understand, so I won't explain it, and then the execution result is as follows:

Python demo.py

Open Wg

Start to play DNF, account number: horse monkey, password: 888888

The knife cuts the body, the heart cuts the soul.

Close Wg

Falling: the mournful cannon of Qiugu

Open Wg

Start playing World of Warcraft, race: blood elves, class: Paladin, server: echo Hill, camp: tribe

For the glory of Sindoulei

Close Wg

Fall: Ashbringer

Process finished with exit code 0

two。 Function execution of multiple decorators

How will a function be executed if it is decorated by multiple decorators?

Def wrapper1 (fn): def inner (* args, * * kwargs): print ('this is w1 entry') ret = fn (* args, * * kwargs) print ('this is w1 out') return ret return innerdef wrapper2 (fn): def inner (* args, * * kwargs): print ('this is w2 entry') ret = fn (* args * * kwargs) print ('this is w2 going out') return ret return inner@wrapper1@wrapper2def target (): print ('I am the target') if _ _ name__ ='_ _ main__': target ()

Give the execution order directly:

The execution order in which a function is decorated by multiple decorators

# w1 w2 target w2 w1

3. Decorator with parameters

The syntax of the decorator allows us to provide other parameters, such as @ decorator (a), when we call. In this way, it provides more flexibility for the writing and use of the decorator.

(there is another layer of function on it)

For example, we can specify the log level in the decorator, because different business functions may require different log levels.

Def use_logging (level): def decorator (func): def wrapper (* args * * kwargs): if level= = "warn": logging.warn ("% s is running"% func.__name__) elif level= = "info": logging.info ("% s is running"% func.__name__) return func (* args) return wrapper return decorator@use_logging (level= "warn") def Foo (name='foo'): print ("I am% s"% name) foo () 4. Class decorator

Yes, the decorator can be not only a function, but also a class. Compared with the function decorator, the class decorator has the advantages of flexibility, high cohesion, encapsulation and so on. Using the class decorator relies mainly on the class's _ _ call__ method, which is called when the decorator is attached to a function using the @ form.

Class Foo (object): def _ init__ (self, func): self._func = func def _ call__ (self): print ('class decorator runing') self._func () print (' class decorator ending') @ Foodef bar (): print ('bar') bar () above is all the content of the article "sample Analysis of python decorator Code". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to 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