In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is Python3 namespace and scope". The explanation in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian and go deep into it slowly to study and learn "what is Python3 namespace and scope" together!
namespace
Namespaces are mappings from names to objects, and most namespaces are implemented through Python dictionaries.
Namespaces provide a way to avoid name conflicts in your project. Each namespace is independent and has no relationship, so there can be no duplicate names in a namespace, but different namespaces can have duplicate names without any impact.
Let's take an example in a computer system, a folder (directory) can contain multiple folders, each folder can not have the same file name, but the files in different folders can be renamed.
There are generally three namespaces:
Built-in names, Python built-in names, such as function names abs, char, exception names BaseException, and so on.
Global names are names defined in modules that record module variables, including functions, classes, other imported modules, module-level variables, and constants.
Local names are names defined in a function that record the variables of the function, including parameters of the function and locally defined variables. (Also defined in class)
Namespace lookup order:
Assuming we want to use the variable runoob, Python's search order is: local namespaces go-> global namespaces-> built-in namespaces.
If the variable runoob cannot be found, it will abandon the lookup and raise a NameError exception:
NameError: name 'runoob' is not defined。
Namespace lifecycle:
The lifecycle of a namespace depends on the scope of the object and ends when the object completes execution.
Therefore, we cannot access objects from the internal namespace from the external namespace.
Instance # var1 is the global name var1 = 5def some_func(): # var2 is a local name var2 = 6 def some_inner_func(): # var3 is an embedded local name var3 = 7
As the following illustration shows, the same object name can exist in multiple namespaces.
scope
A scope is an area of the body of a Python program that has direct access to a namespace.
In a Python program, direct access to a variable will access all scopes from the inside out until it is found, otherwise it will report an undefined error.
In Python, program variables are not accessible everywhere; access depends on where the variable is assigned.
The scope of a variable determines which part of the program can access which particular variable name. Python has four scopes:
There are four scopes:
L (Local): The innermost layer, containing local variables, such as the interior of a function/method.
E (Enclosing): Contains variables that are non-local and non-global. For example, two nested functions, a function (or class) A contains a function B, then the scope of A is nonlocal for the name in B.
G (Global): The outermost layer of the current script, such as the global variables of the current module.
B (Built-in): Contains built-in variables/keywords, etc., Finally searched.
Rule order: L -> E -> G ->gt; B.
If you can't find it locally, you will find it locally outside the local area (such as closure), and if you can't find it, you will find it globally, and then you will find it in the built-in area.
g_count = 0 #global scope def outer(): o_count = 1 #in functions outside closure functions def inner(): i_count = 2 #local scope
Built-in scope is implemented through a standard module called builtin, but the variable name itself is not in built-in scope, so you must import the file to use it. In Python 3.0, you can use the following code to see which variables are predefined:
>>> import builtins>>> dir(builtins)
Python only module (module), class (class) and function (def, lambda) will introduce new scope, other code blocks (such as if/elif/else/, try/except, for/while, etc.) will not introduce new scope, that is to say, variables defined in these statements can also be accessed externally, as follows:
>>> if True:... msg = 'I am from Runoob'... >>> msg'I am from Runoob'>>>
The msg variable in the example is defined in the if statement block, but the outside is still accessible.
If msg is defined in a function, it is a local variable and cannot be accessed externally:
>>> def test():... msg_inner = 'I am from Runoob'... >>> msg_innerTraceback (most recent call last): File "", line 1, inNameError: name 'msg_inner' is not defined>>>
From the error message, it shows that msg_inner is undefined and cannot be used because it is a local variable and can only be used within a function.
Global and local variables
Variables defined inside a function have a local scope, and variables defined outside a function have a global scope.
Local variables can only be accessed inside the function they are declared in, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope. Examples include:
Example (Python 3.0+)#!/ usr/bin/python3 total = 0 #This is a global variable #writable function description def sum( arg1, arg2 ): #Returns the sum of two parameters. " total = arg1 + arg2 # total is a local variable here. print ("function is local variable: ", total) return total #Call sum function sum( 10, 20 )print ("function outside is global variable: ", total)
The output of the above example:
Local variables inside function: 30 Global variables outside function: 0
global and nonlocal keywords
When an inner scope wants to modify an outer scope variable, the global and nonlocal keywords are used.
The following example modifies the global variable num:
Example (Python 3.0+)#!/ usr/bin/python3 num = 1def fun1(): global num #requires global keyword declaration print(num) num = 123 print(num)fun1()print(num)
The output of the above example:
1123123
If you want to modify variables in nested scope (enclosing scope, outer non-global scope), you need the nonlocal keyword, as follows:
Example (Python 3.0+)#!/ usr/bin/python3 def outer(): num = 10 def inner(): nonlocal num # nonlocal keyword declaration num = 100 print(num) inner() print(num)outer()
The output of the above example:
100100
In a special case, suppose the following code is run:
Example (Python 3.0+)#!/ usr/bin/python3 a = 10def test(): a = a + 1 print(a)test()
The above procedure is executed, and the error message is as follows:
Traceback (most recent call last): File "test.py", line 7, intest() File "test.py", line 5, in test a = a + 1UnboundLocalError: local variable 'a' referenced before assignment
The error message is a local scope reference error, because the a in the test function is local and undefined, and cannot be modified.
Modify a as a global variable, pass it through the function parameter, and the output result can be executed normally:
Example (Python 3.0+)#!/ usr/bin/python3 a = 10def test(a): a = a + 1 print(a)test(a)
The output of the execution is:
11 Thank you for reading, the above is "Python3 namespace and scope is what" content, after the study of this article, I believe that we have a deeper understanding of what Python3 namespace and scope is, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.