Python UnboundLocalError

时间:2013-11-14 15:41:33

标签: python

def blah(self, args):
    def do_blah():
        if not args:
            args = ['blah']
        for arg in args:
            print arg  

上面提到错误if not args说UnboundLocalError:在赋值之前引用了局部变量'args'。

def blah(self, args):
    def do_blah():
        for arg in args:       <-- args here
            print arg  

但是尽管使用args

,这仍然有效

为什么第一个不使用if not args:中的blah's args?

1 个答案:

答案 0 :(得分:3)

问题是当python在函数内部看到赋值时,它会将该变量视为局部变量,并且在执行函数时不会从封闭或全局范围中获取其值。

args = ['blah']

foo = 'bar'
def func():
    print foo    #This is not going to print 'bar'
    foo = 'spam'  #Assignment here, so the previous line is going to raise an error.
    print foo
func()    

<强>输出:

  File "/home/monty/py/so.py", line 6, in <module>
    func()
  File "/home/monty/py/so.py", line 3, in func
    print foo
UnboundLocalError: local variable 'foo' referenced before assignment

请注意,如果foo是一个可变对象,并且您尝试对其执行就地操作,那么python就不会抱怨。

foo = []
def func():
    print foo
    foo.append(1)
    print foo
func()  

<强>输出:

[]
[1]

文档:Why am I getting an UnboundLocalError when the variable has a value?