Python error: local variable ‘XXXX’ referenced before assignment

Recently, this error was encountered in coding: local variable ‘XXX’ Referenced before assignment, which solved this problem by looking up materials. This blog is very clear, so I collect it for you to view later.


Referenced Before Assignment Local Variable ‘XXX’ Referenced Before Assignment Local Variable ‘XXX’ Referenced Before Assignment Local Variable ‘XXX’ Referenced Before Assignment

[python] view plain copy
xxx = 23  
def PrintFileName(strFileName):   
    if xxx == 23:  
        print strFileName  
        xxx = 24  

PrintFileName("file")  

Error means that the variable ‘XXX’ is not defined before the reference. The global keyword in Python is used to refer to global variables, so I tried it, and it worked: * * * * * * * * * * * * * * * * * * * *

[python] view plain copy
xxx = 23  
def PrintFileName(strFileName):  
    global xxx  
    if xxx == 23:  
        print strFileName  
        xxx = 24  

PrintFileName("file")  

In Python, if you change the value of a variable with the same global name, it will become a local variable. The reference to that variable will be undefined before you change it. If you want to reference a global variable, and if you want to change it, you must include the global keyword.
The original link: http://blog.csdn.net/magictong/article/details/4464024


Added:
defines global variables in the class:

a = 1 
class File(object): 
    def printString(self,str): 
        global a  
        if a == 1:  
            print str  
            a = 24          
f = File()             
f.printString("file")  

Read More: