不明白为什么会发生UnboundLocalError(关闭) [英] Don't understand why UnboundLocalError occurs (closure)

查看:102
本文介绍了不明白为什么会发生UnboundLocalError(关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做什么错了?

counter = 0

def increment():
  counter += 1

increment()

以上代码抛出 UnboundLocalError

推荐答案

Python没有变量声明,因此必须找出变量本身的范围。它通过一个简单的规则来执行此操作:如果在函数内部对变量进行了赋值,则该变量被视为局部变量。 [1] 因此,该行

Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line

counter += 1

隐含 counter increment()本地。但是,尝试执行此行将尝试在分配局部变量 counter 之前读取它的值,从而导致 UnboundLocalError [2]

implicitly makes counter local to increment(). Trying to execute this line, though, will try to read the value of the local variable counter before it is assigned, resulting in an UnboundLocalError.[2]

如果计数器是全局变量,则 global 关键字会有所帮助。如果 increment()是局部函数,而 counter 是局部变量,则可以使用 nonlocal 在Python 3.x中。

If counter is a global variable, the global keyword will help. If increment() is a local function and counter a local variable, you can use nonlocal in Python 3.x.

这篇关于不明白为什么会发生UnboundLocalError(关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆