ProgramingTip

정식에서 할당 오류 전에 참조 됨

bestdevel 2020. 12. 7. 20:31
반응형

정식에서 할당 오류 전에 참조 됨


Python에서 다음 오류가 발생합니다.

UnboundLocalError: local variable 'total' referenced before assignment

(오류가 발생하는 파일 함수 앞)에서 전역 키워드를 사용하여 'total'을 선언합니다. 그런 다음 프로그램 본문에서 'total'을 사용하는 함수가 호출되기 전에 0으로 지정합니다. 여러 곳에서 0으로 설정해 보았습니다. ),하지만 작동하지 않습니다. 내가 뭘 잘못하고 있는지 보는 사람이 있습니까?


나는 당신이 '글로벌'을 사용하고 있다고 생각합니다. Python 참조를 참조 하십시오 . 전역 변수없이 변수를 선언 한 다음 전역 변수에 액세스 후보 함수 내에서 선언해야합니다 global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

이 예를 참조하십시오.

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

전체적으로doA() 수정하지 않기 때문에 11이 아닌 1입니다.


내 시나리오

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] //access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   //these won't

    inner()

참고 URL : https://stackoverflow.com/questions/855493/referenced-before-assignment-error-in-python

반응형