UnboundLocalError가 발생하는 이유를 이해하지 못함
이 질문에는 이미 답변이 있습니다.
- 변수가 이미 정의 된 후 변경하는 방법은 무엇입니까? 답변 6 개
- 함수에서 전역 변수 사용 18 답변
내가 여기서 뭘 잘못하고 있니?
counter = 0
def increment():
counter += 1
increment()
위의 코드는를 던집니다 UnboundLocalError.
파이썬에는 변수 선언이 없으므로 변수 자체 의 범위 를 파악해야 합니다. 간단한 규칙에 따라 수행됩니다. 함수 내부에 변수에 할당이 있으면 해당 변수는 로컬로 간주됩니다. [1] 따라서 선
counter += 1
암시 적으로로 counter로컬합니다 increment(). 그러나이 줄을 실행하려고하면 지역 변수 counter가 할당되기 전에 지역 변수의 값을 읽으려고 시도하여 결과를 얻습니다 UnboundLocalError. [2]
경우 counter글로벌 변수의 global키워드는 도움이 될 것입니다. 경우 increment()로컬 함수이며 counter지역 변수, 당신이 사용할 수있는 nonlocal파이썬 3.x를에
로컬 변수 대신 글로벌 변수 카운터를 수정 하려면 글로벌 명령문 을 사용해야합니다 .
counter = 0
def increment():
global counter
counter += 1
increment()
에 counter정의 된 둘러싸는 범위가 전역 범위가 아닌 경우 Python 3.x에서 nonlocal 문을 사용할 수 있습니다 . 파이썬에 같은 상황에서 당신은 로컬이 아닌 이름으로 재 할당 할 방법이 없습니다 2.x에서 counter당신이 할 필요가 있으므로, counter가변 및 수정 :
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
제목 줄에있는 질문에 답하기 위해 * 그렇습니다. 파이썬에는 함수 내부에만 적용되며 (파이썬 2.x에서는) 읽기 전용입니다. 이름을 다른 개체에 다시 바인딩 할 수는 없습니다 (개체를 변경할 수있는 경우 내용을 수정할 수 있음). Python 3.x에서는 nonlocal키워드를 사용하여 클로저 변수를 수정할 수 있습니다 .
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
* 질문은 파이썬에서 클로저에 대해 독창적으로 물었습니다.
코드가 왜 발생하는지에 대한 이유는 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)
Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword).
A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.
In your case you are trying to treat counter as a local variable rather than a bound value. Note that this code, which binds the value of x assigned in the enclosing environment, works fine:
>>> x = 1
>>> def f():
>>> return x
>>> f()
1
To modify a global variable inside a function, you must use the global keyword.
When you try to do this without the line
global counter
inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.
Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.
try this
counter = 0
def increment():
global counter
counter += 1
increment()
Python is not purely lexically scoped.
See this: Using global variables in a function other than the one that created them
and this: http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/
참고URL : https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs
'IT story' 카테고리의 다른 글
| 백 스택에 추가 될 때 어떻게 프래그먼트 상태를 유지할 수 있습니까? (0) | 2020.06.13 |
|---|---|
| 패널 또는 PlaceHolder 사용 (0) | 2020.06.13 |
| node.js, SSL을 사용한 socket.io (0) | 2020.06.13 |
| Bash의 eval 명령 및 일반적인 용도 (0) | 2020.06.13 |
| git 리포지토리를 GitLab에서 GitHub로 옮길 수 있습니까? (0) | 2020.06.13 |