Python Closure decorator

Source: Internet
Author: User

1. What is a closure?
Multi-layer function nesting, (function is also defined function, usually two), often the inner layer function will use the outer function of the variable, the inner layer function and the variables of the external function as a special object, this is the closure. Closures are more pure and lightweight than object-oriented, with both data and code to execute data, and more powerful than normal functions, not only code but also data;
2. Anonymous functions, common functions, closures, object-oriented differences?
1). Anonymous functions can perform basic simple functions, and passing is the function of reference only.
2). Normal functions can accomplish more complex functions, and passing is the function of reference only.
3). Closures are capable of transferring more complex functions, which are functions and data in this closure.
4). Objects can accomplish the most complex functions, the transfer is data + function, but occupy a lot of space, wasting resources.
3. What is an adorner?
Using the principle of closure, a target function is decorated, that is, to perform some specific things before and after executing a target function.
Examples of common adorners are:
def set_func (func):
Print ("---to start decorating")
def call_func (*args, Kwargs):
Print ("---this is what you do before the target function----") # If you need to
ret = func (*args, * Kwargs) # Unpacking
Print ("---this is what happens after the target function----") # If you need it
Return RET # You can add a return value if you need a return value
Return Call_func
@set_func # equivalent to test1 = Set_func (test1)
def test1 (
args,
Kwargs):
"" "function inside to do function" ""
Return "OK" # returns none if needed

Python Closure decorator

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.