python中带有运算符和函数编程的UnboundLocalError(方法工作正常)

2024-04-26 01:18:11 发布

您现在位置:Python中文网/ 问答频道 /正文

项目1.py:

def runf(f):
    f()

def main():
    l = [0]
    def f():
        l.append(1)
    runf(f)
    print(l)

main()

给我(如预期):

[0, 1]

项目2.py:

def runf(f):
    f()

def main():
    l = [0]
    def f():
        l += [1] # <-- Only difference
    runf(f)
    print(l)

main()

给了我:

Traceback (most recent call last):
  File "prog2.py", line 11, in <module>
    main()
  File "prog2.py", line 8, in main
    runf(f)
  File "prog2.py", line 2, in runf
    f()
  File "prog2.py", line 7, in f
    l += [1]
UnboundLocalError: local variable 'l' referenced before assignment

有人能给我解释一下这是怎么回事吗?你知道吗

注意:这在python2和python3中都会发生。你知道吗

另外,我也愿意为这个问题提供更好的标题。你知道吗


Tags: 项目inpymostonlymaindefline
1条回答
网友
1楼 · 发布于 2024-04-26 01:18:11

Python的execution model reference(第4.1节)说明:

If a name is bound in a block, it is a local variable of that block.

所发生的是l += [1],为了结合,等价于l = l + [1],这意味着lf内被结合。下面是另一个有趣的document reference

Assignment of an object to a single target is recursively defined as follows.

If the target is an identifier (name):

  • If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace.
  • Otherwise: the name is bound to the object in the current global namespace.

否则子句与此相关。由于您没有在f的范围内声明global l并将其分配给l,因此名称绑定在f的本地命名空间中。然后,由l += [1]隐式创建的对它的引用引用引用了一个尚未定义的变量。因此UnboundLocalError。你知道吗


顺便说一句,global l帮不了你。Python3有nonlocal语句来处理如下情况:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

相关问题 更多 >