Use python to implement a simple Cache System

Source: Internet
Author: User

View Original article:

Http://www.ibaiyang.org/2013/01/04/python-decorator-introduction/

BenArticleOfCodeNo highlight. Check the original text. The format is better.

This article will introduce the decorator in Python. In this article, we will be familiar with the basic methods and examples of using decorator, and use decorator to implement an advanced example-Cache System ).

Decorator can simplify the encoding volume and increase the readability of the Code in some way, which is why the modifier magic is introduced in Python. Let's take a look at the following example:

 
DefFoo(Self):PassFoo=Classmethod(Foo)

It can be seen that the above code structure makes people look uncomfortable. If you use a decorator, everything will become beautiful.

@ ClassmethodDefFoo(Self):Pass

In python, decorator is a python object used to modify functions and class methods. The decorator can be divided into functions and class decorator. The only restriction on the decorator is its callable. We know that the function itself is callable, therefore, if you use a class decorator, you must implement the _ call _ method of the class.

The decorator must be used in a proper place; otherwise, it cannot be very effective. For example, we need to use the decorator to implement the following functions:

 
DefValue():Return"Hello world! "

Make the output result

 
<H1> <li>Hello world!</LI> 

Then we can create the following decorator:

DefLi(Func):Return"<Li>"+Func()+"</LI>"DefH1(Func):Return"<H1>"+Func()+"</H1>"

Then you can call

@ H1@ LiDefValue():Return"Hello world! "PrintValue()

This increases the readability of the code and enhances the reusability of the Code.

After reading some simple usage methods, we can use mathematical languages to describe the decorator.

 
@ F1(ARG)@ F2DefFunc():Pass

Equivalent

DefFunc():PassFunc=F1(ARG)(F2(Func))

At the beginning, I was not very interested in the decorator because we can implement its functions in other ways after all, however, I accidentally came into contact with the cache system using the decorator, which suddenly gave me the advantages and advantages of the decorator.

Assume that we have the following recursion to implement the recursion of fibonacci_number.

DefFIB(N):IfN<2:Return1ReturnFIB(N-1)+FIB(N-2)

What is the problem with this recursion? We know that recursion usually produces many identical sub-calls, so we need a cache to save the intermediate results, which can accelerate the recursion process.

Let's compare the pre-and post-recursive call processes after the cache system is used. Take fib (5) as an example:

 

 

 

 

 

 

 

 

 

 

 

 

We can see that the sub-process of repeated calls disappears. I also compared the time with profile, which is much faster, especially when the FIB parameter is larger, the following is a simple version of how to implement the cache system:

 From  Functools  Import  Wraps  Def  Cache  (  Func  ):  Caches  =  {}  @ Wraps  ( Func  )  Def  Wrap  (*  ARGs  ):  If  ARGs  Not  In  Caches  :  Caches  [  ARGs  ]  =  Func  (*  ARGs  )  Return Caches  [  ARGs  ]  Return  Wrap 

Easy to use

  @ cache   def   fib   (  n  ):   If   n     2  :   return   1   return   fib   (  n  -  1  )   +   fib   (< /span>  n  -  2 
     )   Print   fib   (  5  )   # Call fib so easy!  

We can see from the above that we have implemented a simple cache system without any code modifications. Remember that without any code modifications, in addition, not all recursion methods are suitable for this type of method. For example, binary trees are not necessary. it is meaningful to use this method only when repeated subprocess calls are used.

Reference:

    • Http://code.activestate.com/recipes/577479-simple-caching-decorator/
    • Http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/

----------------- Create high-quality articles. pay more attention to the wine ---------------

To create high-quality articles, please RecommendationCome on .... Thank you. Please pay attention to my subsequent articles, which will be even better.

Sina Weibo: http://weibo.com/baiyang26

The wine ghost official blog: http://www.ibaiyang.org [recommended to use Google Reader subscription]

Pour wine into the official Douban: http://www.douban.com/people/baiyang26/

If you want to repost this blog,Please specify the source

If you have any comments or suggestions on this article,Leave a message

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.