【问题标题】:Why does a global list variable is updated in global scope inside a function without using global line?为什么全局列表变量在函数内部的全局范围内更新而不使用全局行?
【发布时间】:2020-08-27 11:17:09
【问题描述】:

我最近遇到了一个全球性问题,我不知道 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 在全局范围内更新而其他变量没有?

【问题讨论】:

标签: python list scope global


【解决方案1】:

您尚未在函数中定义 list_variable_2 ,因此 python 无法在该范围内找到该变量。如果发生这种情况,python 会在其范围之外进行搜索。

搜索的顺序如下

  1. 本地:如果您在函数内部引用 x,则解释器 首先在其本地的最内层范围内搜索它 功能。
  2. 封闭:如果 x 不在本地范围内但出现在 驻留在另一个函数中的函数,然后是解释器 在封闭函数的范围内搜索。
  3. 全局:如果两者都不是 上面的搜索是卓有成效的,然后解释器在 接下来是全局范围。
  4. 内置:如果在其他任何地方都找不到 x,则 解释器尝试内置作用域。

来源 https://realpython.com/python-namespaces-scope

【讨论】:

    【解决方案2】:

    请按照 LEGB 规则确认: https://realpython.com/python-scope-legb-rule/

    在您的情况下,函数内的 list_variable_1 是本地命名空间中的新列表 但是对于 list_variable_2,您正在访问 list_variable_2 的每个元素并对其进行更改。

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 2017-03-05
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2016-11-13
      • 2015-03-22
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多