Python Decorator Decorating principle Quest

Source: Internet
Author: User
Tags closure python decorator

I haven't had time to write a blog lately, and this blog has been lying in the draft box for a while, with just one headline.
Now I'm finally going to start writing.

  1. Why do you write this article?

    The previous period of time staring at the Python Learning Group, found that many students are not very understanding of Python a lot of content, feel the need to share their time through learning practice summed up some things.
    Write the process I will be some of their own understanding of the content directly written out, feel that there is no need to copy and paste some conceptual things, if there is a misunderstanding of the place, welcome you in the message points together to discuss the improvement, so nonsense not to write it.

  2. What is an adorner?

    Adorner (Decorator): Personal understanding adorner is nothing more than a function, function is to pass in a source function, throw back a closed package containing the function of the original function to replace the original function for invocation.
    Oh, and pull out a closure concept. ⊙﹏⊙ b Khan about closures next time you're free, write another article.

  3. Categories of adorners

    An example of an adorner that implements a very boring function (which controls the number of function runs)

    • Adorner with no parameters

      An adorner with no parameters is a truly mounted decorator, which returns a closure instead of the original function by passing in a function, and the adorner with no parameters is defined as follows:

      def my_decorator(func):    li = list()    limit = 5    def inner(*args, **kwargs):        # do some thing        li.append(1)        if len(li) > limit:            print(‘<%s>只能被调用%s次‘ % (func.__name__, limit))            return        else:            return func(*args, **kwargs)    return inner@my_decoratordef my_func1(n):    print(‘n is %s‘ % n)def my_func2(n):    print(‘func2 n is %s‘ % n)for i in range(10):    my_func1(i)    my_func2(i)

      Execution results

      n is 0func2 n is 0n is 1func2 n is 1n is 2func2 n is 2n is 3func2 n is 3n is 4func2 n is 4<my_func1>只能被调用5次func2 n is 5<my_func1>只能被调用5次func2 n is 6<my_func1>只能被调用5次func2 n is 7<my_func1>只能被调用5次func2 n is 8<my_func1>只能被调用5次func2 n is 9

      Limit execution times by returning a inner closure

    • Adorner with parameters

      The adorner function with parameters is not really a decorator in its own right, and the adorner function with parameters is actually a function that returns a value as an adorner function.
      Why should I have an adorner with parameters?
      Take the example above: Although the my_decorator implementation of the function is more boring, but I still feel that this boring function is not perfect, because the function of the number of execution limit in the adorner is written dead, if I want to limit several different functions, each function limit the number of executions, Then the number of times each limit is executed according to the adorner without parameters I have to re-write an adorner, which is obviously very unreasonable. So I need an adorner with parameters to do this.
      The following are the functions that implement this function:

      def my_decorator(limit):    def outer(func):        li = list()        def inner(*args, **kwargs):            # do some thing            li.append(1)            if len(li) > limit:                print(‘<%s>只能被调用%s次‘ % (func.__name__, limit))                return            else:                return func(*args, **kwargs)        return inner    return outer@my_decorator(2)def my_func1(n):    print(‘n is %s‘ % n)@my_decorator(4)def my_func2(n):    print(‘func2 n is %s‘ % n)for i in range(5):    my_func1(i)    my_func2(i)

      Sharp-eyed's classmates may have noticed that there are different decorations and without parameters, the adorner function name that is directly followed by @ after the @, where the adorner function name is followed by a pair of parentheses and arguments.
      With parentheses and arguments means that the function has been executed, equivalent to the return value of the function execution followed by the @, so the outer function that the My_decorator function returns is the actual adorner function,
      With the My_decorator parameter limit we can specify a different maximum number of function executions each time a function is decorated.
      Execution results

      n is 0func2 n is 0n is 1func2 n is 1<my_func1>只能被调用2次func2 n is 2<my_func1>只能被调用2次func2 n is 3<my_func1>只能被调用2次<my_func2>只能被调用4次
  4. About the "@" symbol

    • @ symbol Action

      The @ symbol is a syntactic sugar in python that makes it easier to read the code in order to make it easier to write a decorative statement.
      Place the @ symbol before the function definition, followed by an adorner function name that represents the function being decorated by the adorner, which is equivalent to executing a statement immediately after the function definition:
      Func=decorator (func)
      Here func is the decorated function, and decorator is the adorner function.
    • The @ symbol is a handicap for beginners

      @ symbol all kinds of convenience but for beginners to understand the decorator brought a certain barrier: beginners are easy to forget the actual role of @, and then will not think how the decorator is exactly how to decorate.
      So in fact this obstacle is the main reason I write this article.

  5. Decorating process for decorators

    Finally wrote to the point, the subject or to limit

Python Decorator Decorating principle Quest

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.