Python 3 的“nonlocal”关键字:深入探究
“nonlocal”关键字在 Python 3 中具有重要用途,提供对在封闭范围内声明的变量,而不使用保留的全局关键字。这种细致入微的功能允许对嵌套函数内的变量引用进行特殊控制。
揭示非局部的角色
考虑以下不带“nonlocal”关键字的代码片段:
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
执行时,此代码会产生以下结果输出:
inner: 2 outer: 1 global: 0
正如您所观察到的,内部函数中的变量“x”独立于外部函数中的变量“x”。这是因为内部函数的“x”变量在其自己的作用域内优先。
相反,引入“nonlocal”关键字会改变行为:
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
通过此修改,输出更改为:
inner: 2 outer: 2 global: 0
“nonlocal”关键字允许内部函数引用和修改在外部声明的“x”变量
非局部与全局
必须注意“非局部”和“全局”之间的区别。虽然这两个关键字都允许从嵌套范围访问变量,但它们有不同的用途。 “nonlocal”限制对仅在封闭范围中定义的变量的访问,而“global”提供对全局范围中定义的变量的访问。
为了更好地理解,请考虑使用“global”关键字的以下代码:
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
在这种情况下,输出变为:
inner: 2 outer: 1 global: 2
“global”关键字将“x”全局绑定到 true声明的变量,覆盖任何具有相同名称的局部或封闭变量。
结论
Python 3 中的“nonlocal”关键字提供了一个强大的工具来管理变量引用嵌套函数。它使在封闭范围内声明的变量可以在内部范围内访问和修改,从而对复杂代码结构中的变量使用提供更精细的控制。
以上是Python 3 的'nonlocal”关键字与嵌套函数作用域中的'global”有何不同?的详细内容。更多信息请关注PHP中文网其他相关文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载
最流行的的开源编辑器

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)