In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "what the decorator code is like in Python". It is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn what the decorator code is like in Python.
First, understand the decorator
Everything is an object (functions can be passed as objects)
Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.
Def function_one (): print ("test function") # can assign a function to a variable, such as foo = function_one # there are no parentheses here, because we are not calling the function_one function, but putting it in the foo variable. Foo () 'test function Process finished with exit code 0destroy'
The concept of closure:
1) function nesting
2) Internal functions use variables of external functions
3) the return value of the external function is the internal function
Example:
Def outer_function (message): def inner_function (): print (message) return inner_functionfunc = outer_function ("Hello") func () # Hello II, decorator prototype
The function of the decorator is to add new functions to the original function without modifying the source code and the way the original function is called.
# pass the function as an argument to another function def decorator_function (original_function): def wrapper_function (): print ('wrapper executed this before {}' .format (original_function.__name__)) original_function () return wrapper_function''returns wrapper_function instead of wrapper_function (); this is because when you put a pair of parentheses after it, the function executes However, if you don't put parentheses after it, it can be passed everywhere and can be assigned to other variables without executing it. '' def display (): print ('display function ran') decorator_display = decorator_function (display) decorator_display ()
Running result:
Wrapper executed this before displaydisplay function ranProcess finished with exit code 01, decorator def decorator_function (original_function): def wrapper_function (): print ('wrapper executed this before {}' .format (original_function.__name__)) original_function () return wrapper_function@decorator_functiondef display (): # equivalent to display = decorator_function (display) print ('display function ran') display ()
Running result:
Wrapper executed this before display
Display function ran
Process finished with exit code 0
two。 Decorated function def decorator_function (original_function): def wrapper_function (* args,**kwargs): print ('wrapper executed this before {}' .format (original_function.__name__)) original_function (* args,**kwargs) return wrapper_function@decorator_functiondef display (): print ('display function ran') @ decorator_functiondef display_info (name,age): print (' display_info ran with arguments ({}) {}) '.format (name,age)) display () print (' ='* 50) display_info ('Michal',20)
Running result:
Wrapper executed this before display
Display function ran
=
Wrapper executed this before display_info
Display_info ran with arguments (Michal,20)
Process finished with exit code 0
There is a problem running the following code
Def decorator_function (original_function): def wrapper_function (* args,**kwargs): print ('wrapper executed this before {}' .format (original_function.__name__)) original_function (* args,**kwargs) return wrapper_function@decorator_functiondef display (): print ('display function ran') @ decorator_functiondef display_info (name,age): print (' display_info ran with arguments ({}, {}) '.format (name) Age)) display_info = decorator_function (display_info) print (display_info.__name__)
Wrapper_function
Process finished with exit code 0
The output should be display_info, where the function is replaced by wrapper_function, rewriting our function name and comment document (docstring). Functools.wraps can be used in Python to solve this problem.
From functools import wrapsdef decorator_function (original_function): @ wraps (original_function) def wrapper_function (* args,**kwargs): print ('wrapper executed this before {}' .format (original_function.__name__)) original_function (* args,**kwargs) return wrapper_function@decorator_functiondef display (): print ('display function ran') @ decorator_functiondef display_info (name,age): print (' display_info ran with arguments ({}) {}) '.format (name,age)) display_info = decorator_function (display_info) print (display_info.__name__)
Running result:
Display_info
Process finished with exit code 0
3. Decorator with parameters
Embed a decorator in a function
From functools import wrapsdef logit (logfile='out.log'): def logging_decorator (func): @ wraps (func) def wrapped_function (* args, * * kwargs): log_string = func.__name__ + "was called" print (log_string) # Open logfile And write the content with open (logfile,'a') as opened_file: # now type the log to the specified logfile opened_file.write (log_string +'\ n') return func (* args) * * kwargs) return wrapped_function return logging_decorator@logit () def myfunc1 (): passmyfunc1 () # Output: myfunc1 was called# now a file called out.log appears The content is the above string @ logit (logfile='func2.log') def myfunc2 (): passmyfunc2 () # Output: myfunc2 was called# now a file called func2.log appears, and the content is the above string 4. Use class as decorator class myDecorator (object): def _ init__ (self, f): print ("inside myDecorator.__init__ ()") f () # Prove that function definition has completed def _ call__ (self): print ("inside myDecorator.__call__ ()") @ myDecorator def aFunction (): print ("inside aFunction ()") print ("Finished decorating aFunction ()") aFunction ()
Running result:
Inside myDecorator.__init__ () inside aFunction () Finished decorating aFunction () inside myDecorator.__call__ () Process finished with exit code 0
The decorated function aFunction () is actually an object of class myDecorator. When the aFunction () function is called again, the object of the class myDecorator is actually called, so the _ _ call__ () method of the class myDecorator is called.
Therefore, when using a class as a decorator function to add some additional attributes or functions to a function, it is common to record the incoming function in the class's _ _ init__ () method, and then call the decorated function and other additional processing in _ _ call__ ().
Class entryExit (object): def _ init__ (self, f): self.f = f def _ call__ (self): print ("Entering", self.f.__name__) self.f () print ("Exited") Self.f.__name__) @ entryExit def func1 (): print ("inside func1 ()") @ entryExit def func2 (): print ("inside func2 ()") func1 () func2 ()
Running result:
Entering func1
Inside func1 ()
Exited func1
Entering func2
Inside func2 ()
Exited func2
Process finished with exit code 0
5. Use objects as decorators
Empty parameter:
From functools import wrapsclass decorator_class: def _ _ init__ (self): print ('execute _ _ init__ () method of decorator_class class') def _ _ call__ (self, original_function): print ('execute _ _ call__ () method of decorator_class class') @ wraps (original_function) def wrapped_function (* args * * kwargs): print ('call method executed this before {}' .format (original_function.__name__)) print ('execute' + original_function.__name__ +'()) original_function (* args, * * kwargs) print (original_function.__name__ +'() execution completed') return wrapped_function@decorator_class () def display_info (name Age): print ('display_info ran with arguments ({}, {})' .format (name,age)) display_info ('Michael',20)
The running results are as follows:
Execute the _ _ init__ () method of the decorator_class class
Execute the _ _ call__ () method of the decorator_class class
Call method executed this before display_info
Execute display_info ()
Display_info ran with arguments (Michael,20)
Display_info () execution completed
Process finished with exit code 0
With parameters:
From functools import wrapsclass decorator_class: def _ _ init__ (self,arg1, arg2): print ('execute _ _ init__ () method of decorator_class class') self.arg1 = arg1 self.arg2=arg2 def _ _ call__ (self, original_function): print ('execute _ _ call__ () method of decorator_class class') @ wraps (original_function) def wrapped_function (* args * * kwargs): print ('execute wrapped_function ()') print ('call method executed this before {}' .format (original_function.__name__)) print ('decorator parameters:', self.arg1, self.arg2) print ('execute' + original_function.__name__ +'()') original_function (* args * * kwargs) print (original_function.__name__ +'() execution completed') return wrapped_function@decorator_class ('Hello',' World') def display_info (name,age): print ('display_info ran with arguments ({}, {})' .format (name,age)) display_info ('Michael',20)
The running results are as follows:
Execute the _ _ init__ () method of the decorator_class class
Execute the _ _ call__ () method of the decorator_class class
Execute wrapped_function ()
Call method executed this before display_info
Decorator parameter: Hello World
Execute display_info ()
Display_info ran with arguments (Michael,20)
Display_info () execution completed
Process finished with exit code 0
Example 2:
From functools import wrapsclass logit (object): def _ init__ (self, logfile='out.log'): self.logfile = logfile def _ call__ (self, func): @ wraps (func) def wrapped_function (* args * * kwargs): log_string = func.__name__ + "was called" print (log_string) # Open logfile and write to with open (self.logfile 'a') as opened_file: # now type the log to the specified file opened_file.write (log_string +'\ n') # now Send a notification self.notify () return func (* args, * * kwargs) return wrapped_function def notify (self): # logit logs only, no other pass@logit () def myfunc1 (): pass6. Nesting of multi-layer decorators # decorator 1def decorator1 (func): # defines the function def wrapper1 () after decoration: # decorator 1 print ('1-before decoration 1') # calls the basic function func () # extended function 2 print ('1-after decoration 1') return wrapper1# Decorator 2def decorator2 (func): # define the function after decoration def wrapper2 (): # decorator 2 print ('2-before decoration 2') # call the basic function func () # extend function 2 print ('2-after decoration 2') return wrapper2# basic function @ decorator2 # Step 2: test = decorator2 (eat) = test2@decorator1 # step 1: test = decorator1 (eat) = test1def test (): print ('test') # call function test ()
Running result:
2-before Decoration 2
1-before Decoration 1
test
1-after Decoration 1
2-after Decoration 2
Process finished with exit code 0
The above is all the content of this article "what is the decorator code in Python?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.