Unbound Local Error with global variable

前端 未结 3 1902
别跟我提以往
别跟我提以往 2021-01-12 05:26

I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:

The variables, REDGOLD

相关标签:
3条回答
  • 2021-01-12 05:54

    You need to declare the variable as global in each scope where they are being modified

    Better yet find a way to not use globals. Does it make sense for those to be class attributes for example?

    0 讨论(0)
  • 2021-01-12 05:59

    Found that variables in main act like global "read only" variables in function. If we try to reassign the value, it will generate error.

    Try:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
    
    f()
    

    It's ok.

    But:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
        A = [1,1,1,1,1]
    
    f()
    

    Generate

      File "./test.py", line 6, in f
        print A[RED]
    UnboundLocalError: local variable **'A'** referenced before assignment
    

    and:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
        RED = 2
    
    f()
    

    Generate

      File "./test.py", line 6, in f
        print A[RED]
    UnboundLocalError: local variable **'RED'** referenced before assignment
    
    0 讨论(0)
  • 2021-01-12 06:13

    global make the global variable visible in the current code block. You only put the global statement in main, not in attack.

    ADDENDUM

    Here is an illustration of the need to use global more than once. Try this:

    RED=1
    
    def main():
        global RED
        RED += 1
        print RED
        f()
    
    def f():
        #global RED
        RED += 1
        print RED
    
    main()
    

    You will get the error UnboundLocalError: local variable 'RED' referenced before assignment.

    Now uncomment the global statement in f and it will work.

    The global declaration is active in a LEXICAL, not a DYNAMIC scope.

    0 讨论(0)
提交回复
热议问题