Python非本地语句

本文翻译自: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 = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

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

def counter_generator():
    count = 0
    while True:
        count += 1
        yield 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 = 1
    def inner():
        x = 2
        print("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 = 1
    def inner():
        nonlocal x
        x = 2
        print("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 program

def f():
    a = 0          #2. nonlocal with respect to function g
    def g():
        nonlocal a
        a=a+1
        print("The value of 'a' using nonlocal is ", a)
    def h():
        global a               #3. using global variable
        a=a+5
        print("The value of a using global is ", a)
    def i():
        a = 0              #4. variable separated from all others
        print("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. 奇怪的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值