相关疑难解决方法(0)

Python变量范围错误

以下代码在Python 2.5和3.0中按预期工作:

a, b, c = (1, 2, 3)

print(a, b, c)

def test():
    print(a)
    print(b)
    print(c)    # (A)
    #c+=1       # (B)
test()
Run Code Online (Sandbox Code Playgroud)

但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值ab被正确地打印.这让我感到困惑,原因有两个:

  1. 为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?

  2. 为什么变量ab打印符合预期,同时c引发错误?

我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c

有人可以解释一下这种行为吗?

python variables scope

195
推荐指数
7
解决办法
6万
查看次数

Python 嵌套函数中的变量作用域

第一个代码片段打印[0, 3]出来。

def func():
    a = [0]

    def swim():
        a.append(3)
        # a = [1]+a
        return a
    return swim()

print(func())
Run Code Online (Sandbox Code Playgroud)

第二个代码片段引发错误“UnboundLocalError:赋值前引用的局部变量‘a’”

def func():
    a = [0]

    def swim():
        # a.append(3)
        a = [1]+a
        return a
    return swim()

print(func())
Run Code Online (Sandbox Code Playgroud)

到底a功能是否可见/可访问?swim

python scope function global-variables python-3.x

5
推荐指数
1
解决办法
4036
查看次数

Python:list.extend和list .__ iadd__之间的区别

我认为list.extend列表中的"+ ="基本上做同样的事情 - 扩展列表而不创建新列表.

我希望下面的代码可以打印,[42, 43, 44, 45, 46]但我得到了UnboundLocalError: local variable 'x' referenced before assignment

为什么我收到此错误?区别在哪里?

def f():
    x.extend([43, 44])
def g():
    x += ([45, 46])
x = [42]
f()
g()
print x
Run Code Online (Sandbox Code Playgroud)

我在python2.7.3和python3.4.0中尝试过这个.

python

3
推荐指数
1
解决办法
497
查看次数