Python packet closure function

Source: Internet
Author: User
Tags closure

Closed Package

Closures: Closures in Python are defined (interpreted) from the expression form as:

If in an intrinsic function, a reference is made to a variable that is in an outer scope (but not at the global scope), then the intrinsic function is considered a closure (closure).

Look at a function first:

def func1 ()     def func2 ()         a = 1         return a     func2 ()

Because there are nested functions inside the function,
nested function definitions: functions defined inside cannot be called globally
So there's a closure problem.
What's the problem?
Is that func1 can't get FUNC2 's variable A.
How do you get it?
We know that a function is the first class of objects (the first kind of object you can use as a variable), you can put the variable in the FUNC1 (FUNC2) through return

def func1 ()     def func2 ()         a = 1         return a     return func2  x = func1 ()    #这样就拿到了func2 and assigned to the variable x x ()        # x () equivalent to FUNC2 ()      See    If you get a return value a   so you get the FUNC2 variable a  and if: def func1 (para1)     para1     def func2 ()         A = 1         return para1 + a     return Func2  func1 (5)    #如果把5传给func1    will pack def FUNC2 this function,     # Note:             def func2 ()                 a = 1 return                 1 + a func1 (5) ()  #等同于func2 () #就变相调用函数func2 ()  Gets the return value of 6 print (FUNC1 (5 ) ()  # 6  #如果func1 (8),   then Func2 packaged:         def func2 ()             a = 1             return 8 + a #每次调用func1, It will return (package) A new closure instance so: closure = function + Reference environment

  

Python packet closure function

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.