Python Namespaces and Scopes

Source: Internet
Author: User

First, the name space

definition : Name-to-object mapping. A namespace is an implementation of a dictionary, a key is a variable name, and a value is a value that corresponds to a variable. The namespaces are independent of each other and cannot have names in a namespace, but different namespaces can have duplicate names without any effect.

Classification:

1. Global namespace:

The namespace that is created when code is run.

2. Local namespaces:

A temporary space, such as a function, that is opened during a program's operation.

3. Built-in namespaces:

Open space for storing commonly used built-in methods, such as input,print,str,list, which are variables of the built-in namespaces before the program runs the load code

Plus loading sequence:   load Order: Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called) Order of values: In the local call: Local namespace, global namespace, built-in namespaces, Global Call: Built-in namespaces, global namespaces

  

Second, scope

Global scope: Contains built-in namespaces, global namespaces , can be referenced anywhere throughout the file, are globally valid

Local scope: Local namespace, only valid locally

Global keyword, nonlocal keyword.

Global

1, declare a global variable.

2, Global (limited to string, number) is required when local scope wants to make a modification to a globally scoped global variable.

Nonlocal:

1, global variables cannot be modified.

2, in the local scope, the variables of the parent scope (or the outer scope non-global scope) are referenced and modified, and which layer of the reference, from that layer and the following this variable all changed.

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.