[英]Why does a global list variable is updated in global scope inside a function without using global line?
我最近遇到了一个全球性问题,我不知道 python 中的这种行为:
# declaring some global variables
variable = 'peter'
list_variable_1 = ['a','b']
list_variable_2 = ['c','d']
def update_global_variables():
"""without using global line"""
variable = 'PETER' # won't update in global scope
list_variable_1 = ['A','B'] # won't get updated in global scope
list_variable_2[0]= 'C' # updated in global scope surprisingly this way
list_variable_2[1]= 'D' # updated in global scope surprisingly this way
update_global_variables()
print('variable is: %s'%variable) # prints peter
print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b']
print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D']
为什么list_variable_2
在全局范围内更新而其他变量没有?
您尚未在函数中定义 list_variable_2,因此 python 无法在该范围内找到该变量。 如果发生这种情况,python 会在其范围之外进行搜索。
它搜索的顺序如下
请承认 LEGB 规则: https ://realpython.com/python-scope-legb-rule/
在您的情况下,函数中的 list_variable_1 是本地命名空间中的新列表,但对于 list_variable_2,您正在访问 list_variable_2 的每个元素并对其进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.