When will python decorator be used?

Source: Internet
Author: User
Tags python decorator
Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Reply: this is a list of official Python decorator instances. you can see the various useful functions of the decoratorlibrary: PythonDecoratorLibrary. Basically, you can think of everything.

There are similar categories:
1. inject parameters (default parameters are provided to generate parameters)
2. record function behavior (log, cache, timing or something)
3. pre-processing/post-processing (configuration context or something)
4. modify the context when calling (asynchronous or parallel threads, class methods)

The decorator is actually a function, a function used to wrap the function, and returns a modified function object. It is often used in scenarios with cut-plane requirements. typical scenarios include log insertion, performance testing, and transaction processing. The decorator is an excellent design for solving such problems. with the decorator, we can extract a large number of identical codes irrelevant to the function itself and continue to reuse them. In summary, the purpose of the decorator is to add additional functions to existing objects.


Let's take a look at a small example:

def alan():    print('alan speaking')
Share One of my notes: Python annotator notes (I think the layout here is not good. if you want to carefully read it, you can click the previous link to jump to the short book)
================

I. function decorators
1. start with the Python internal function.

First, let's discuss What Inner Functions-What Are They Good?(Chinese version)

Three benefits of using inner functions
  • Encapsulation
  • Implementing the DRY principle
  • Closures and factory functions

1. encapsulation

Def outer (num1): def inner_increment (num1): # hidden from outer code return num1 + 1 num2 = inner_increment (num1) print (num1, num2) inner_increment (10) # cannot run correctly # outer (10) # can run normally
You can use it to change the functions of an existing function. You can add functions before and after the function is called to generate a new function based on the previous function.

For example:

def addOne(func):def wraper(*args,**kwargs):saySmthing = "Result :"return saySmthing +" "+ str(func(*args,**kwargs)) return wraper@addOnedef func(a,b):return a+b  print(func(10,20))
When you are lazy.

The decorator can easily inject some code (similar to aop) into a process, which can centrally control the behavior of the original functions or classes and facilitate global Singleton and exception handling. Let's talk about one of them.
@ Classmethod
Modify a class member function. after modification, a class global function similar to C ++ can be called without instantiating an object.
The decorator is added to Python 2.4, which makes it easier to read and understand function and method encapsulation (receiving a function and returning a function in the enhanced version. In the original use case, you can define a method as a class method or a static method in the definition header.
Common decorator modes include:
  • Parameter check;
  • Cache;
  • Proxy;
  • Context provider.

Python advanced programming (Douban) P37-46
If you do not want to read English documents, you can read this book. For example, when binding events and event handlers in PyQt
@ QtCore. pyqtSlot ()
Def on_btnOpen_clicked (self ):
Pass
In this way, you don't need to display the connect. let's take a look at the flask framework. The decorator uses the fly. In particular, request routing. It is like an auxiliary army in a battle. Regular Army workers help the army to work on edge materials. The parts related to your program logic are placed in the regular military function. However, some auxiliary logic is irrelevant to the main logic and highly repetitive. it is unclear to put it in the main function. It is made into a decoration device, which is elegant to use and conforms to the aesthetics of python.

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.