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

if not args上面在说 UnboundLocalError: local variable 'args' referenced before assignment时会引发错误。

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

但这仍然有效,尽管使用args

为什么第一个不使用 blah 的参数 in if not args:

4

1 回答 1

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]

文档:为什么当变量有值时我会收到 UnboundLocalError?

于 2013-11-14T15:43:53.647 回答