Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数中的python变量作用域_Python_Python 3.x_Scope - Fatal编程技术网

函数中的python变量作用域

函数中的python变量作用域,python,python-3.x,scope,Python,Python 3.x,Scope,我发现了一个类似的问题。它与不可变变量有关。但当我测试可变变量时,我不知道Python解释器如何决定变量的范围 以下是我的示例代码: def test_immutable(): a = 1 b = 2 def _test(): print(a) print(b) a += 1 print(a) _test() def test_mutable(): _dict = {} de

我发现了一个类似的问题。它与不可变变量有关。但当我测试可变变量时,我不知道Python解释器如何决定变量的范围

以下是我的示例代码:

def test_immutable():
    a = 1
    b = 2

    def _test():
        print(a)
        print(b)

        a += 1
        print(a)

    _test()

def test_mutable():
    _dict = {}

    def _test():
        print(_test.__dict__)

        _dict['name'] = 'flyer'

         print('in _test: {0}'.format(_dict['name']))

    _test()

    print(_dict['name'])


if __name__ == '__main__':
    # test_immutable()    # throw exception
    test_mutable()    # it's ok
不可变与可变与变量范围无关。变量只是名称,并且总是以相同的方式工作。范围甚至是在编译时决定的,早在Python知道要分配给它们什么之前


两个函数之间的区别在于,第一个函数使用
+=
运算符直接分配给
a
,这会导致
a
成为本地函数。第二个问题分配给
\u dict
中的一个键,该键最终调用dict对象上的一个方法,并且不影响变量的作用域。

您的问题与链接的问题相同。一种情况是分配变量,另一种情况是引用变量。