Python modifier getting started tutorial (nine steps), python nine steps

Source: Internet
Author: User
Tags python decorator

Python modifier getting started tutorial (nine steps), python nine steps

Decorator is an advanced Python syntax. The decorator Can process a function, method, or class. In Python, we have multiple methods to process functions and classes. For example, in the Python closure, we can see the function object as the return result of a function. Compared with other methods, the decorator has simple syntax and high code readability. Therefore, the decorator is widely used in Python projects.

This is the content introduced in the Python Learning Group. It is a good way to learn and practice more.

Step 1: Prepare the simplest function and add additional functions.

#-*-Coding: gbk-*-''' Example 1: The simplest function, indicating that two '''def myfunc (): print ("myfunc () called. ") myfunc ()

Step 2: Use the decoration function to add additional functions before and after function execution

#-*-Coding: gbk-*-''' Example 2: The parameter used to replace the function (decoration) decoration function is the decorated function object. The actual statement of the decoration of the original function object is returned: myfunc = deco (myfunc) ''' def deco (func): print ("before myfunc () called. ") func () print (" after myfunc () called. ") return funcdef myfunc (): print (" myfunc () called. ") myfunc = deco (myfunc) myfunc ()

Step 3: Use the syntax sugar @ to describe the function

#-*-Coding: gbk-*-''' Example 3: Use the syntax sugar @ to decorate the function, which is equivalent to "myfunc = deco (myfunc) but we found that the new function was called only for the first time, and the original function called '''def deco (func): print ("before myfunc () called. ") func () print (" after myfunc () called. ") return func @ decodef myfunc (): print (" myfunc () called. ") myfunc ()

Step 4: Use nested packaging functions to ensure that each new function is called

#-*-Coding: gbk-*-''' Example 4: Use nested function packaging to ensure that each new function is called. The parameters and return values of nested function packaging are the same as those of the original function, the decoration function returns the nested packaging function object '''def deco (func): def _ deco (): print ("before myfunc () called. ") func () print (" after myfunc () called. ") # You do not need to return func. Actually, you should return the return value of the original function: return _ deco @ decodef myfunc (): print (" myfunc () called. ") return 'OK' myfunc ()

Step 5: Describe the functions with Parameters

#-*-Coding: gbk-*-''' Example 5: Describe the function with parameters. The parameters and return values of the nested function are the same as those of the original function, the decoration function returns the nested packaging function object '''def deco (func): def _ deco (a, B): print ("before myfunc () called. ") ret = func (a, B) print (" after myfunc () called. result: % s "% ret) return retreturn _ deco @ decodef myfunc (a, B): print (" myfunc (% s, % s) called. "% (a, B) return a + bmyfunc (1, 2) myfunc (3, 4)

Step 6: Describe functions with uncertain number of parameters

#-*-Coding: gbk-*-''' Example 6: decorate a function with an uncertain number of parameters. Use the parameter (* args, ** kwargs ), automatically adapt to variable parameters and named parameters ''' def deco (func): def _ deco (* args, ** kwargs): print ("before % s called. "% func. _ name _) ret = func (* args, ** kwargs) print ("after % s called. result: % s "% (func. _ name __, ret) return retreturn _ deco @ decodef myfunc (a, B): print ("myfunc (% s, % s) called. "% (a, B) return a + B @ decodef myfunc2 (a, B, c): print (" myfunc2 (% s, % s, % s) called. "% (a, B, c) return a + B + cmyfunc (1, 2) myfunc (3, 4) myfunc2 (1, 2, 3) myfunc2 (3, 4, 5)

Step 7: Bring parameters to the decorator

#-*-Coding: gbk-*-''' Example 7: On the basis of example 4, let the ornament carry parameters. Compared with the previous example, there is an additional layer of packaging in the outer layer. The decoration function name should actually be more meaningful ''' def deco (arg): def _ deco (func): def _ deco (): print ("before % s called [% s]. "% (func. _ name __, arg) func () print ("after % s called [% s]. "% (func. _ name __, arg) return _ decoreturn _ deco @ deco ("mymodule") def myfunc (): print ("myfunc () called. ") @ deco (" module2 ") def myfunc2 (): print (" myfunc2 () called. ") myfunc () myfunc2 ()

Step 8: Let the ornament carry Class Parameters

#-*-Coding: gbk-*-''' Example 8: The modifier has the class parameter '''class locker: def _ init _ (self ): print ("locker. _ init _ () shoshould be not called. ") @ staticmethoddef acquire (): print (" locker. acquire () called. (This is a static method) ") @ staticmethoddef release (): print (" locker. release () called. (object instance not required) ") def deco (cls): ''' cls must implement the acquire and release static method ''' def _ deco (func ): def _ deco (): print ("before % s called [% s]. "% (func. _ name __, cls) cls. acquire () try: return func () finally: cls. release () return _ decoreturn _ deco @ deco (locker) def myfunc (): print ("myfunc () called. ") myfunc ()

Step 9: decorator includes class parameters and splits public classes into other py files. It also demonstrates how to apply multiple decorator to a function.

#-*-Coding: gbk-*-''' mylocker. py: public class for example 9. py '''class mylocker: def _ init _ (self): print ("mylocker. _ init _ () called. ") @ staticmethoddef acquire (): print (" mylocker. acquire () called. ") @ staticmethoddef unlock (): print (" mylocker. unlock () called. ") class lockerex (mylocker): @ staticmethoddef acquire (): print (" lockerex. acquire () called. ") @ staticmethoddef unlock (): print (" lockerex. unlock () called. ") def lockhelper (cls): ''' cls must implement the acquire and release static methods ''' def _ deco (func): def _ deco (* args, ** kwargs): print ("before % s called. "% func. _ name _) cls. acquire () try: return func (* args, ** kwargs) finally: cls. unlock () return _ decoreturn _ deco #-*-coding: gbk -*-

''' Example 9: the decorator carries class parameters and splits public classes into other py files.

It also demonstrates how to apply multiple decorators ''' to a function '''

from mylocker import *class example:@lockhelper(mylocker)def myfunc(self):print(" myfunc() called.")@lockhelper(mylocker)@lockhelper(lockerex)def myfunc2(self, a, b):print(" myfunc2() called.")return a + bif __name__=="__main__":a = example()a.myfunc()print(a.myfunc())print(a.myfunc2(1, 2))print(a.myfunc2(3, 4)) 

I have shared with you the Python annotator getting started tutorial (nine steps). I hope it will be helpful to you.

Articles you may be interested in:
  • Introduction to functions and function parameters of the python decorator
  • Example of using the python decorator
  • Python retries decorator example
  • Use the python decorator to verify the configuration file example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.