PYTHON__ Namespaces and Scopes

Source: Internet
Author: User

One: function nesting, in the process of calling a function, another call to other functions

def bar ():
Print (' from Bar ')
def foo ():
Print (' from foo ')
Bar ()
Foo ()
The use of nested functions, broken down into the smallest operation, one call


Two: nested definition of function: Inside a function, a function is defined.
Def f1 ():
x = 1
def f2 ():
Print (' from F2 ')
F2 ()
F1 ()

The name space, where the name is stored, the exact name space is where the name and the value of the variable are bound
Built-in namespaces: Python's own name, generated when the Python interpreter starts, and contains some python built-in names
Global namespace: The name of the file-level definition at the time the file is executed
Local namespaces: During the execution of a file, if a function is called, the namespace of the function is generated, which is used to hold the name defined within the function, which takes effect when the function is called and expires after the call has ended.
Load order: Built-in namespace------> global Namespace-----> local namespace
Name Lookup Order: Local namespace------> global Namespace-----> built-in namespaces


Four: scope, range of effects
Global scope: Global survival, globally valid
Local scope: Local survival, locally valid
Def f1 ():
x = 1
y = 2
Print (Locals ())
Print (Globals ())
F1 ()
Print (Locals ())
Print (Globals ())
Print (Locals () is globals ())
Change the global name:
x = 1
Def f1 ():
Global X
x = 2
F1 ()
Print (x)

Change local name:

Def f1 ():
x = 1
def f2 ():
x = 2
Def f3 ():
Nonlocal x# is the value directly above the function.
x = 3
F3 ()
F2 ()
F1 ()


V: precedence, fixed at function definition, independent of call location
x = 1
Def f1 ():
def f2 ():
Print (x)
return F2
Func = F1 ()
Func ()


































PYTHON__ 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.