本文翻译自:Python nonlocal statement

What does the Python nonlocal statement do (in Python 3.0 and later)? Python nonlocal语句有什么作用(在Python 3.0及更高版本中)?

There's no documentation on the official Python website and help("nonlocal") does not work, either. 官方Python网站上没有文档,并且help("nonlocal")也不起作用。


#1楼

参考:https://stackoom.com/question/5IGp/Python非本地语句


#2楼

In short, it lets you assign values to a variable in an outer (but non-global) scope. 简而言之,它使您可以将值分配给外部(但非全局)范围内的变量。 See PEP 3104 for all the gory details. 有关所有血腥细节,请参阅PEP 3104 。


#3楼

A google search for "python nonlocal" turned up the Proposal, PEP 3104 , which fully describes the syntax and reasoning behind the statement. 谷歌搜索“ python nonlocal”,提出了提案PEP 3104 ,该提案完整描述了该语句背后的语法和推理。 in short, it works in exactly the same way as the global statement, except that it is used to refer to variables that are neither global nor local to the function. 简而言之,它的作用与global语句完全相同,不同之处在于,它用于引用既不是全局变量也不是函数局部变量的变量。

Here's a brief example of what you can do with this. 这是您可以执行此操作的简短示例。 The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures. 可以将计数器生成器重写为使用它,以便它看起来更像是带有闭包的语言惯用法。

def make_counter():count = 0def counter():nonlocal countcount += 1return countreturn counter

Obviously, you could write this as a generator, like: 显然,您可以将其编写为生成器,例如:

def counter_generator():count = 0while True:count += 1yield count

But while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. 但是,尽管这是完全习惯用的python,但对于初学者来说,第一个版本似乎更加明显。 Properly using generators, by calling the returned function, is a common point of confusion. 通过调用返回的函数正确使用生成器是一个常见的困惑点。 The first version explicitly returns a function. 第一个版本显式返回一个函数。


#4楼

Compare this, without using nonlocal : 比较一下,不使用nonlocal

x = 0
def outer():x = 1def inner():x = 2print("inner:", x)inner()print("outer:", x)outer()
print("global:", x)# inner: 2
# outer: 1
# global: 0

To this, using nonlocal , where inner() 's x is now also outer() 's x : 为此,使用nonlocal ,其中inner()x现在也是outer()x

x = 0
def outer():x = 1def inner():nonlocal xx = 2print("inner:", x)inner()print("outer:", x)outer()
print("global:", x)# inner: 2
# outer: 2
# global: 0

If we were to use global , it would bind x to the properly "global" value: 如果我们使用global ,它将x绑定到正确的“ 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 

#5楼

a = 0    #1. global variable with respect to every function in programdef f():a = 0          #2. nonlocal with respect to function gdef g():nonlocal aa=a+1print("The value of 'a' using nonlocal is ", a)def h():global a               #3. using global variablea=a+5print("The value of a using global is ", a)def i():a = 0              #4. variable separated from all othersprint("The value of 'a' inside a function is ", a)g()h()i()
print("The value of 'a' global before any function", a)
f()
print("The value of 'a' global after using function f ", a)

#6楼

@ooboo: @ooboo:

It takes the one "closest" to the point of reference in the source code. 它与源代码中的参考点“最接近”。 This is called "Lexical Scoping" and is standard for >40 years now. 这称为“词法作用域”,现在已经有40多年的历史了。

Python's class members are really in a dictionary called __dict__ and will never be reached by lexical scoping. Python的类成员确实在名为__dict__的字典中,并且无法通过词法作用域来访问。

If you don't specify nonlocal but do x = 7 , it will create a new local variable "x". 如果您未指定nonlocal本地变量,但x = 7 ,它将创建一个新的本地变量“ x”。 If you do specify nonlocal , it will find the "closest" "x" and assign to that. 如果您确实指定nonlocal ,它将找到“最近”“ x”并分配给它。 If you specify nonlocal and there is no "x", it will give you an error message. 如果您指定nonlocal并且没有“ x”,它将给您一条错误消息。

The keyword global has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. 关键字global在我看来一直很陌生,因为它会很乐意忽略除最外面的一个以外的所有其他“ x”。 Weird. 奇怪的。

Python非本地语句相关推荐

  1. python基本语法语句-Python基本语句

    一.Python 条件语句 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: Python程序语言指定任何非 ...

  2. python while循环语句-Python While 循环语句

    Python While 循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件(cond ...

  3. python语言if语句-Python2 if 条件语句

    程序在一般情况下是按顺序执行的,就像流水账一样,一条一条顺序运行 当然,有时候我们需要根据条件来有选择的执行某些语句,或者重复执行某些语句 Python 提供了各种控制结构,允许更复杂的执行路径 条件 ...

  4. python的for循环语句_干货丨Python的循环语句基础讲解!

    我们知道计算机程序语言一般是按照顺序执行的,那么编程语言就提供了各种控制结构,允许更复杂的执行路径,其中循环语句的作用就是允许我们执行一个语句或语句组多次. 在Python中循环语句的类型主要有以下几 ...

  5. python中if语句的实例_对python中if语句的真假判断实例详解

    说明 在python中,if作为条件语句,当if后面的条件参数为真时,则执行后面的语句块,反之跳过,为了深入理解if语句,我们需要知道if语句的真假判断方式. 示例 在python交互器中,经过测试发 ...

  6. [转载] python中的且语句_简单探讨python中的语句和语法

    参考链接: 在Python中解包:并行分配之外 python程序结构 python"一切皆对象",这是接触python听到最多的总结了.在python中最基层的单位应该就是对象了, ...

  7. Python While 循环语句

    Python While循环语句 Python 编程中while语句用于循环执行程序,即在一些条件下,循环执行一些段程序,以处理需要重复处理的相同任务. 执行语句可以是单个语句或语句块. 判断条件可以 ...

  8. Android中实现非本地图片的点击态

    2019独角兽企业重金招聘Python工程师标准>>> 对于本地图片我们可以通过selector来轻松的实现点击态. 但是在我们的项目中,一个关于对非本地图片的点击态实现还是难倒了不 ...

  9. python 3.x语句print_Python 3.x语句print(1,2,3,sep=’.’)

    Python 3.x语句print(1,2,3,sep='.') 答:0.0430902777777778 甄氏被曹丕赐死的主要原因是与曹植有染 答:× 将500mg糖原样品用放射性(K14CN)处理 ...

最新文章

  1. APUE(第五章)标准IO
  2. solaris下使用USB 海量存储设备
  3. 关于面象接口编程的理解
  4. bltoolkit mysql_.NET 轻量级 ORM 框架 - Dapper 介绍
  5. XtraBackup原理解读
  6. oracle delete 空间增加,实战经验:关于Oracle Delete数据后空间重用问题的测试
  7. 汇编语言-010(循环移位ROL,ROR 、进位循环进位RCL,RCR 、有符号数溢出 、双精度移位SHLD,SHRD、SHL和ADD计算 、位运算应用)
  8. webpack 读取文件夹下的文件_webpack基本介绍及使用
  9. linux 解决端口占用
  10. 深度学习笔记(11) 超参数调试
  11. C Tricks(十七)—— 对角线元素的屏蔽、二维数组(矩阵)的遍历
  12. UnityShader13:渐变与遮罩
  13. Linux——vim使用及账号用户管理
  14. 磁盘分区——MBR详解(私密)
  15. 坦克类游戏的制作之路
  16. C++ 模板中的类型获取(一)
  17. ICWPT 2022 | 从技术突破到生态构建,小米坚持做充电领域的拓荒者和领先者
  18. wkhtmltopdf使用指南,html转图片,转pdf
  19. ssh-keygen -t rsa -C xxxx@xxxx.com解释
  20. Python爬虫的实际运用之:破解滑动验证码

热门文章

  1. 实操高校数据中心vsphere6.0升级6.5,重新规划网络。
  2. Jos pipe实现解析
  3. java实现栈的数据结构
  4. android 多语言(在APP里面内切换语言)
  5. css知多少(2)——学习css的思路
  6. 单向关系中的JoinColumn
  7. 比较 Python(Python 与其他语言的比较)
  8. Redis遍历所有key的两个命令 -- KEYS 和 SCAN
  9. MongoDB Sharding 机制分析
  10. nyoj 谁是最好的Coder