当前位置:网站首页>Namespace and scope
Namespace and scope
2022-06-28 12:33:00 【Life needs depth】
Namespace
Let's take a look at the official document :
A namespace is a mapping from names to objects.Most namespaces are currently implemented as Python dictionaries.
Namespace (Namespace) It's a mapping from name to object , Most of the namespace is through Python Dictionary to achieve .
Namespaces provide a way to avoid name conflicts in projects . Each namespace is independent , It doesn't matter , Therefore, a namespace cannot have duplicate names , But different namespaces can duplicate names without any effect .
Let's take an example from a computer system , A folder ( Catalog ) Can contain multiple folders , Each folder cannot have the same file name , But the file name in the folder can be different .

There are generally three namespaces :
- Built in name (built-in names), Python Language built-in names , Like the function name abs、char And exception name BaseException、Exception wait .
- Global name (global names), The name defined in the module , Module variables recorded , Include function 、 class 、 Other imported modules 、 Module level variables and constants .
- Local name (local names), The name defined in the function , The variables of the function are recorded , Including parameters of functions and locally defined variables .( Class is also defined in )

Namespace lookup order :
Suppose we want to use variables runoob, be Python The search order of is : Local namespace -> Global namespace -> Built in namespace .
If the variable is not found runoob, It will discard the search and raise a NameError abnormal :
NameError: name 'runoob' is not defined.
The lifecycle of the namespace :
The lifecycle of a namespace depends on the scope of the object , If the object execution is complete , Then the lifecycle of the namespace ends .
therefore , We cannot access objects with internal namespaces from external namespaces .
example
# var1 Is the global name
var1 = 5
def some_func():
# var2 Is a local name
var2 = 6
def some_inner_func():
# var3 Is the local name of the embedded
var3 = 7
As shown in the figure below , The same object name can exist in multiple namespaces .

Scope
A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" here means that an unqualified reference to a name attempts to find the name in the namespace.
The scope is a Python The program can directly access the body area of the namespace .
In a python In the program , Direct access to a variable , All scopes will be accessed from the inside out until , Otherwise, an undefined error will be reported .
Python in , Program variables are not accessible anywhere , Access depends on where the variable is assigned .
The scope of a variable determines which part of the program can access which specific variable name .Python There are a total of 4 Kind of , Namely :
There are four scopes :
- L(Local): The innermost layer , Contains local variables , Like a function / Methods the internal .
- E(Enclosing): Contains nonlocal (non-local) It's not the whole picture (non-global) The variable of . Like two nested functions , A function ( Or class ) A It contains a function B , So for B For the name of A The scope in is nonlocal.
- G(Global): The outermost layer of the current script , For example, the global variables of the current module .
- B(Built-in): Contains built-in variables / Keywords, etc , It was finally searched .
Rule order : L –> E –> G –> B.
I can't find , Then I will go to the part outside the part to find ( Such as closures ), If you can't find it, you will go to the whole situation , And then go to find .

g_count = 0 # Global scope
def outer():
o_count = 1 # In a function other than a closure function
def inner():
i_count = 2 # Local scope The built-in scope is through a named builtin The standard module of , But the variable name itself is not put into the built-in scope , So you must import this file to use it . stay Python3.0 in , You can use the following code to see which variables are predefined :
>>> import builtins >>> dir(builtins)
Python There are only modules in (module), class (class) And function (def、lambda) To introduce a new scope , Other code blocks ( Such as if/elif/else/、try/except、for/while etc. ) No new scopes will be introduced , In other words, the variables defined in these statements , It can also be accessed from the outside , The following code :
>>> if True: ... msg = 'I am from Runoob' ... >>> msg 'I am from Runoob' >>>
In the example msg Variables are defined in if In the block , But the outside is still accessible .
If you will msg Defined in a function , Then it is a local variable , No access from outside :
>>> def test(): ... msg_inner = 'I am from Runoob' ... >>> msg_inner Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'msg_inner' is not defined >>>
From the wrong information , Illustrates the msg_inner Undefined , Can't use , Because it's a local variable , Can only be used inside a function .
Global and local variables
Variables defined within a function have a local scope , Define a global scope outside the function .
Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope . The following example :
example (Python 3.0+)
#!/usr/bin/python3 total = 0 # This is a global variable # Write function description def sum( arg1, arg2 ): # return 2 The sum of parameters ." total = arg1 + arg2 # total Here is the local variable . print (" Function is a local variable : ", total) return total # call sum function sum( 10, 20 ) print (" Outside the function is the global variable : ", total)
The output of the above example :
Function is a local variable : 30 Outside the function is the global variable : 0
global and nonlocal keyword
When the internal scope wants to modify the variables of the external scope , You use global and nonlocal Keyword. .
The following example modifies global variables num:
example (Python 3.0+)
#!/usr/bin/python3 num = 1 def fun1(): global num # Need to use global Keyword declaration print(num) num = 123 print(num) fun1() print(num)
The output of the above example :
1 123 123
If you want to modify the nested scope (enclosing Scope , The outer layer is not a global scope ) The variables in the nonlocal Keyword. , The following example :
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 :
100 100
There is another special case , Suppose the following code is run :
example (Python 3.0+)
#!/usr/bin/python3 a = 10 def test(): a = a + 1 print(a) test()
The above procedure shall be executed , The error information is as follows :
Traceback (most recent call last):
File "test.py", line 7, in <module>
test()
File "test.py", line 5, in test
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignmentThe error message is local scope reference error , because test Function a Local is used , Undefined , Can't modify .
modify a Is a global variable :
example
#!/usr/bin/python3 a = 10 def test(): global a a = a + 1 print(a) test()
The execution output is :
11
You can also pass... Through function parameters :
example (Python 3.0+)
#!/usr/bin/python3 a = 10 def test(a): a = a + 1 print(a) test(a)
The execution output is :
11
边栏推荐
- Ugui uses tips (VI) unity to realize vertical line display of string
- Beginner level of attack and defense World Hello_ pwn
- 最新汇总!30省份公布2022高考分数线
- Privilege management of vivo mobile phone
- CDC synchronization if the primary key of a database table changes, will it be synchronized into two data or will it be synchronized to update the primary key?
- 【编解码】从零开始写H264解码器(1) 总纲
- FineReport安装教程
- 思源官方付费同步使用指南
- [source code + code comments] error state Kalman filter, extended Kalman filter, gps+imu fusion, EKF eskf gps+imu
- UGUI使用小技巧(六)Unity实现字符串竖行显示
猜你喜欢

ASP.NET CORE Study08

ASP.NET CORE Study05

ASP.NET CORE Study01
![[C language] about scanf() and scanf_ Some problems of s()](/img/d1/e3d0b845e699c8c1fe3eb9f3b250e1.png)
[C language] about scanf() and scanf_ Some problems of s()

group_ Concat learning and configuration

Login interface accesses and clears the token

自定义标题栏View

吐血推荐17个提升开发效率的“轮子”

The paging style flex is set to be displayed at the end (even if the number of pages is longer, there will be no line breaks at the end)

分页样式 flex设置成在尾部显示(即使页数加长 也不会因为在末尾而换行)
随机推荐
【Unity编辑器扩展实践】、查找所有引用该图片的预制体
newest! Introduction and practical tutorial of point cloud processing based on open3d
NFT数字藏品系统开发(3D建模经济模型开发案例)
Map sorting tool class
【C语言】文件读写函数使用
杰理之wif 干扰蓝牙【篇】
命名空间和作用域
UGUI使用小技巧(五) Scroll Rect组件的使用
Beginner level of attack and defense World Hello_ pwn
【编解码】从零开始写H264解码器(1) 总纲
不到一小时,苹果摧毁了15家初创公司
【Unity编辑器扩展基础】、GUILayout
UDP传输rtp数据包丢帧
RemoteViews布局和类型限制源码分析
【Unity编辑器扩展基础】、EditorGUILayout(二)
FineReport安装教程
[source code + code comments] error state Kalman filter, extended Kalman filter, gps+imu fusion, EKF eskf gps+imu
After importing resources, unity also manually modifies the properties of resources? This code can save you a lot of time: assetpostprocessor
Ugui force refresh of layout components
C语言 sprintf函数使用详解