函数中的python变量作用域
我发现了一个类似的问题。它与不可变变量有关。但当我测试可变变量时,我不知道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
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对象上的一个方法,并且不影响变量的作用域。您的问题与链接的问题相同。一种情况是分配变量,另一种情况是引用变量。