Python's function namespaces and scopes

Source: Internet
Author: User

The namespaces are divided into three types:

Global namespaces

Local namespaces

Built-in namespaces

How does the Python code run when it encounters a function?

Once the Python interpreter starts executing, it opens up a space in memory and records the correspondence between the variable name and the value whenever a variable is encountered. But when a function definition is encountered, the interpreter simply reads the function name into memory, indicating that the function exists, and that the variables inside the function and the logical interpreter do not care at all.

---------code at the beginning of the run, the space created to store the "variable name-to-value relationship" is called the global namespace

When executing to a function call, the Python interpreter will open up a memory to store the contents of the function, at which point the variables in the function are stored in the newly opened memory. The variables in the function can only be used inside the function, and all the contents of this memory will be emptied as the function executes.

--------temporary space created in the function's run is called a local namespace .

The built-in namespace holds the Python interpreter's name for us: Input,print,str,list,tuple ... They're all familiar to us, and we can use them to get them.

Order of loading and taking values between three namespaces:

Load Order:

Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: loaded only when called)

Value:

Built-in namespaces, local namespaces, and global namespaces, local call spaces

def input ():     Print (" my own definition of input") def func ():    input () func ()

X =10def  mysum ():    = 2    return= mysum ()print(l)  #2=10def  mysum ():   #  x = 2    return= mysum ()print(l)#Ten
View Code
x = 1def  F (x):    Print(x) F (ten)print(x)

Python's function namespaces and scopes

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.