为了账号安全,请及时绑定邮箱和手机立即绑定

不明白为什么发生UnboundLocalError

不明白为什么发生UnboundLocalError

RISEBY 2019-05-27 13:49:28
不明白为什么发生UnboundLocalError 我在这做错了什么?counter = 0def increment():   counter += 1increment()上面的代码抛出了一个UnboundLocalError。
查看完整描述

4 回答

?
森林海

TA贡献2011条经验 获得超2个赞

Python没有变量声明,因此必须弄清楚变量本身的范围。它通过一个简单的规则来实现:如果对函数内部的变量赋值,则该变量被视为本地变量。[1] 因此,这条线

counter += 1

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

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


查看完整回答
反对 回复 2019-05-27
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

您需要使用全局语句,以便修改全局变量计数器,而不是局部变量:

counter = 0def increment():
  global counter
  counter += 1increment()

如果counter定义的封闭范围不是全局范围,则在Python 3.x上可以使用非本地语句。在Python 2.x的相同情况下,您将无法重新分配到非本地名称counter,因此您需要进行counter可变并修改它:

counter = [0]def increment():
  counter[0] += 1increment()print counter[0]  # prints '1'


查看完整回答
反对 回复 2019-05-27
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

要回答主题中的问题,*是,Python中有闭包,除了它们只适用于函数内部,并且(在Python 2.x中)它们是只读的; 您无法将名称重新绑定到其他对象(但如果该对象是可变的,则可以修改其内容)。在Python 3.x中,您可以使用nonlocal关键字来修改闭包变量。

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter    return increment

increment = incrementer()increment()   # 1increment()   # 2

*原始问题的标题询问了Python中的闭包。


查看完整回答
反对 回复 2019-05-27
?
侃侃无极

TA贡献2051条经验 获得超10个赞

您的代码抛出的UnboundLocalError原因已经在其他答案中得到了很好的解释。

但在我看来,你正试图建立一些类似的东西itertools.count()

那你为什么不尝试一下,看看它是否适合你的情况:

>>> from itertools import count>>> counter = count(0)>>> counter
count(0)>>> next(counter)0>>> counter
count(1)>>> next(counter)1>>> counter
count(2)


查看完整回答
反对 回复 2019-05-27
  • 4 回答
  • 0 关注
  • 1888 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信