Python - UnboundLocalError: local variable referenced before assignment

来源:互联网 发布:关系数据库的基本结构 编辑:程序博客网 时间:2024/05/01 07:45

转载自:点击至wordpress

报了这样一个错

咋办呢

我来告诉你,首先是该问题的简版代码:

#This is valid python 2.5 code#My global variable:USER_COUNT = 0#functions:def Main():      AddUser()def AddUser():  print 'There are',USER_COUNT,'users so far'# actually run Main()Main()


以上代码工作无误,函数AddUser()只是引用了全局变量 USER_COUNT (定义于所有函数域外)。

接下来会看到错误如何产生:当我们试图对全局变量进行写操作或更新时:

 

#USER_COUNT is a GLOBAL variableUSER_COUNT = 0def Main():      AddUser()def AddUser():  USER_COUNT = USER_COUNT + 1  print 'There are',USER_COUNT,'users so far'  Main()


我们得到错误:UnboundLocalError: local variable ‘USER_COUNT’ referenced before assignment

真糟糕!

导致该错误的原因是:只要我们对变量进行写操作,该变量将会被Python自动地看作是当前函数的局部变量(Local Variable)

尽管我们已声明USER_COUNT为全局变量,但由于在AddUser()函数中对USER_COUNT进行写操作(自加1),Python将其后AddUser()函数出现的USER_COUNT都看成是局部变量。

如何解决?

简单,你可以这样做:

#globalUSER_COUNT = 0def Main():      AddUser()def AddUser():  global USER_COUNT ######!!! IMPORTANT !!!  Make sure  # to use the GLOBAL version of USER_COUNT, not some  # locally defined copy of that.  I think this  # might be a python feature to stop functions from  # clobbering the global variables in a program  USER_COUNT = USER_COUNT + 1  print 'There are',USER_COUNT,'users so far'    Main()


在出现更改全局变量的函数中重新声明使用的是全局变量而非局部变量

 

 

 

原创粉丝点击