"Life is short, Python is a song."--python Functional Programming 02

Source: Internet
Author: User

Python scope, local and global variables

First understand that Python can change the scope of the code snippet is def class Lamda If/elif/else try/except/finally for/while

The search path for a variable is: local variable-global variable

Try the following code:

x=100def  Main ():    x+=1    print(x) main ()

When running the above code, there will be an error, for what, you need to understand the scope, local variables and the difference between the global variables

x=100def  Main ():    Global  x    x+=1    print(x) main () Print (x)  #全局变量已被改变

Operation Result: 101101

Because we have added global X, the main () function is able to access the global variable x,

Python closures

Here we have a basic understanding of the Python scope rules

Let's write a closure.

# Python 3.5 def Inc ():  #inc是外围函数    x=0    def  Inner ():   #inner is a nested function        nonlocal x        x+=1        print(x)    return  innerinc1=Inc () INC2 =Inc () INC1 () inc1 () inc1 () Inc2 ()
Run Result:1231

From this example, the intrinsic function is returned directly as a return value, where inc1 is a closure, which is essentially a function, consisting of two parts, a inner function and a variable x, and a closure that keeps the values of these variables in memory.

Why use closures?

Closures avoid the use of global variables, and closures can correlate functions with some of the data they manipulate.

"Life is short, Python is a song"--python Functional programming.

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.