空间装饰代码_最易写出bug?Python命名空间和作用域介绍

本文主要介绍一下Python命名空间和作用域。

简单的说,命名空间就是一种“名称-对象”的映射表,使得我们可以通过对象指定的名称来访问它们。

比如meteoai=666666我们可以用meteoai来访问到具体的值666666

在python中,具体的命名空间就是一个 字典(dictionary) ,它的键就是变量名,它的值就是那些变量的值(对象)。

namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries。

但是命名空间可以相互独立地存在,可以按照一定的层级组织起来,每个命名空间有其对应的作用域。举个简单的例子:

global_a = "I am in global scope" def function_a():    local_a = "I am in function_a"    return local_aprint(global_a)print(function_a())print(local_a) # 局部变量local_a无法在全局空间中被访问到,会报错# output:I am in global scopeI am in function_aNameError: name 'local_a' is not defined

function_a中的变量local_amodule level的变量global_a就在不同的命名空间中,所以print(local_a)会报错。

要想使得local_a可以在函数外部被访问到,只需要加一行代码:

global_a = "I am in global scope" def function_a():    global local_a    local_a = "I am in function_a"    return local_aprint(global_a)print(function_a())print(local_a)# output:I am in global scopeI am in function_aI am in function_a

python中的关键字defclasslamda等能够改变变量作用域,即它们代码块中的变量,不可在外部访问。而 if、 try、 for、 while 等关键字不涉及变量作用域的更改,即它们代码块中的变量,可在外部访问。

而python中对变量命名空间的搜索基于LEGB规则,按此顺序依次进行搜索。首先从当前作用域开始寻找变量,如果没找到就往上一层作用域寻找,没找到就再上一层......

LEGB:

•Local(L): Defined inside function/class•Enclosed(E): Defined inside enclosing functions(Nested function concept)•Global(G): Defined at the uppermost level•Built-in(B): Reserved names in Python builtin modules

即:当前作用域局部变量->外层作用域变量->再外层作用域变量->......->当前模块全局变量->pyhton内置变量,如果还是找不到会抛出NameError异常。

0ea9f7023aa23fed9836f592894988d2.png

a_var = 'global value'def outer():    a_var = 'enclosed value'    def inner():        a_var = 'local value'        print(a_var)    inner()outer()# outputlocal value

所以我们要谨慎使用from a_module import *,因为这条语句向global namespace 导入了一些变量,可能会存在重名变量被覆盖的风险。

global 和 nonlocal

•global: 全局变量•nonlocal: 外层嵌套函数的变量

python 函数中变量的作用域和其他语言类似。如果变量是在函数内部定义的,即为局部变量,只在函数内部有效。一旦函数执行完毕,局部变量就会被回收,无法访问。相对应的,全局变量则是定义在整个文件层次上的,可以在文件内的任何地方被访问,在函数的内部也是可以的。但是我们不能在函数内部随意修改全局变量的值。会报错:

A = 1def func1():    A+=1func1()# outputUnboundLocalError: local variable 'A' referenced before assignment

这是因为python会默认函数的内部变量为局部变量,但发现在函数内部又没有对变量进行声明,所以就会报错。如果要执行这样的操作,需要在函数内部加上global A这个声明。

global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

a_var = 'global value'def a_func():    global a_var    a_var = 'local value'    print(a_var, '[ a_var inside a_func() ]')print(a_var, '[ a_var outside a_func() ]')a_func()print(a_var, '[ a_var outside a_func() ]')# output:global value [ a_var outside a_func() ]local value [ a_var inside a_func() ]local value [ a_var outside a_func() ]

同样的,我们可以使用nonlocal关键字在嵌套函数的内部改变改变嵌套作用域的变量(L改变E中的变量)。

函数的嵌套可以保证内部函数的隐私,内部函数只能被其外部函数所访问,不会暴露在全局作用域中。因此可以用内部函数来封装一些隐私数据,如用户名密码等,可以提高程序的安全性,同时可以提高程序的运行效率。

a_var = 'global value'def outer():    a_var = 'local value'    print('outer before:', a_var)    def inner():        nonlocal a_var         a_var = 'inner value'        print('in inner():', a_var)    inner()    print("outer after:", a_var)outer()## output:outer before: local valuein inner(): inner valueouter after: inner value

使用总结:

1、局部作用域改变全局变量(L中修改G中的变量)用global, global同时还可以定义新的全局变量

2、内层函数改变外层函数变量(在L中修改E中的变量)用nonlocalnonlocal不能定义新的外层函数变量,只能改变已有的外层函数变量,同时nonlocal不能改变全局变量。

闭包(closure)

闭包和前面所说的嵌套函数类似,不同的是,外层函数返回的是一个函数。例如:

def calc_power(n):    def inner_power(base):        return base ** n    return inner_power # 返回值是一个函数calc_square = calc_power(2) # 计算一个数的平方calc_cube = calc_power(3) # 计算一个数的立方 print(calc_square)print(calc_cube)print(f"The square of 6 is {calc_square(6)}")print(f"The cube of 3 is {calc_cube(3)}")# output.inner_power at 0x10cf998c8>.inner_power at 0x10cfd60d0>The square of 6 is 36The cube of 3 is 27

合理使用闭包可以使得代码更加简洁,可读性更好。闭包常常和装饰器(decorator)一起使用。

global variable 和 free variable

global variable是作用范围是整个模块(G)的变量, 而free variable是某个代码块中引用但不是在此处定义的变量。global variable 和 free variable并没有必然的联系。举个例子:

############## example 1############a = 1def func_a():    print(a) # 这里的a是global variable,同时在func_a()中,a也是free variable############## example 2############a = 1def func_b():    a = 2    print(a) # 这里的a分别是global variable和local variable,但是没有free variable############## example 3############def func_c():    a = 1    def func_d():        b = 2        print(a)        print(b)# 在func_d()中a是free variable,但是这里没有全局变量

dir(), globals()和locals()

globals()返回全局的符号表(global symbol table)。locals() 函数会以字典类型返回当前位置的全部局部变量(local symbol table)。

A symbol table is a data structure maintained by a compiler which contains all necessary information about the program.

These include variable names, methods, classes, etc. There are mainly two kinds of symbol table.

1.Local symbol table ==> globals()2.Global symbol table ==> locals()

关于namespace和symbol table:

A symbol table is an implementation detail. Namespaces are implemented using symbol tables, but symbol tables are used for more than just namespaces. For example, functions have their own symbol table for local variables, but those variables do not exist in any namespace (that is, it is impossible to somehow access the local variables of a function using a fully-qualified name). You could say a namespace is a symbol table that can be traversed with simple attribute access alone.

在global scope 中, locals() 和 globals() 返回global namespace的同一个字典。

dir([object]) : Without arguments, return the list of names in the current local scope (similar to locals().keys()). With an argument, attempt to return a list of valid attributes for that object. 不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

print(dir()) # show the names in the module namespace## OUTPUT: ##['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']############################################################print(globals())## OUTPUT: ##{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.sourcefileloader object at>0x10da810f0>, ############################################################locals() == globals()## OUTPUT: ##True############################################################print(list(locals().keys()).sort() == dir().sort())## OUTPUT: ##True############################################################def test_func(arg):        a = 1    print (locals())test_func(666)## OUTPUT: ##{'a': 1, 'arg': 666}############################################################def test_func(arg):        a = 1    print(dir())    print(locals().keys())    print(dir().sort() == list(locals().keys()).sort())test_func(666)## OUTPUT: ##['a', 'arg']dict_keys(['a', 'arg'])True

References

[1] A Beginner's Guide to Python's Namespaces, Scope Resolution, and the LEGB Rule: https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html[2] Global, Local and nonlocal Variables: https://www.python-course.eu/python3_global_vs_local_variables.php

往期推荐

最强大的netCDF处理工具

Python装饰器是个什么鬼?

捍卫祖国领土从每一张地图开始

Nature(2019)-地球系统科学领域的深度学习及其理解

交叉新趋势|采用神经网络与深度学习来预报降水、温度等案例(附代码/数据/文献)

以下是对提供的参考资料的总结,按照要求结构化多个要点分条输出: 4G/5G无线网络优化与网规案例分析: NSA站点下终端掉4G问题:部分用户反馈NSA终端频繁掉4G,主要因终端主动发起SCGfail导致。分析显示,在信号较好的环境下,终端可能因节能、过热保护等原因主动释放连接。解决方案建议终端侧进行分析处理,尝试关闭节电开关等。 RSSI算法识别天馈遮挡:通过计算RSSI平均值及差值识别天馈遮挡,差值大于3dB则认定有遮挡。不同设备分组规则不同,如64T和32T。此方法可有效帮助现场人员识别因环境变化引起的网络问题。 5G 160M组网小区CA不生效:某5G站点开启100M+60M CA功能后,测试发现UE无法正常使用CA功能。问题原因在于CA频点集标识配置错误,修正后测试正常。 5G网络优化与策略: CCE映射方式优化:针对诺基亚站点覆盖农村区域,通过优化CCE资源映射方式(交织、非交织),提升RRC连接建立成功率和无线接通率。非交织方式相比交织方式有显著提升。 5G AAU两扇区组网:与三扇区组网相比,AAU两扇区组网在RSRP、SINR、下载速率和上传速率上表现不同,需根据具体场景选择适合的组网方式。 5G语音解决方案:包括沿用4G语音解决方案、EPS Fallback方案和VoNR方案。不同方案适用于不同的5G组网策略,如NSA和SA,并影响语音连续性和网络覆盖。 4G网络优化与资源利用: 4G室分设备利旧:面对4G网络投资压减与资源需求矛盾,提出利旧多维度调优策略,包括资源整合、统筹调配既有资源,以满足新增需求和提质增效。 宏站RRU设备1托N射灯:针对5G深度覆盖需求,研究使用宏站AAU结合1托N射灯方案,快速便捷地开通5G站点,提升深度覆盖能力。 基站与流程管理: 爱立信LTE基站邻区添加流程:未提供具体内容,但通常涉及邻区规划、参数配置、测试验证等步骤,以确保基站间顺畅切换和覆盖连续性。 网络规划与策略: 新高铁跨海大桥覆盖方案试点:虽未提供详细内容,但可推测涉及高铁跨海大桥区域的4G/5G网络覆盖规划,需考虑信号穿透、移动性管理、网络容量等因素。 总结: 提供的参考资料涵盖了4G/5G无线网络优化、网规案例分析、网络优化策略、资源利用、基站管理等多个方面。 通过具体案例分析,展示了无线网络优化中的常见问题及解决方案,如NSA终端掉4G、RSSI识别天馈遮挡、CA不生效等。 强调了5G网络优化与策略的重要性,包括CCE映射方式优化、5G语音解决方案、AAU扇区组网选择等。 提出了4G网络优化与资源利用的策略,如室分设备利旧、宏站RRU设备1托N射灯等。 基站与流程管理方面,提到了爱立信LTE基站邻区添加流程,但未给出具体细节。 新高铁跨海大桥覆盖方案试点展示了特殊场景下的网络规划需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值