Don't understand why UnboundLocalError occurs

2018-12-30 23:47发布

This question already has an answer here:

What am I doing wrong here?

counter = 0

def increment():
  counter += 1

increment()

The above code throws an UnboundLocalError.

8条回答
心情的温度
2楼-- · 2018-12-31 00:46

try this

counter = 0

def increment():
  global counter
  counter += 1

increment()
查看更多
不流泪的眼
3楼-- · 2018-12-31 00:48

To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal keyword to modify a closure variable.

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

increment = incrementer()

increment()   # 1
increment()   # 2

* The original question's title asked about closures in Python.

查看更多
登录 后发表回答