【问题标题】:Local var available in global scope? [duplicate]全局范围内可用的本地变量? [复制]
【发布时间】:2020-04-16 14:48:31
【问题描述】:

在这段代码 sn-p 中,我忘记在外部范围内定义变量 content。然后我在with 块中为content 赋值。离开with 块后,变量content 的值仍然存在。为什么?

data_dir = "/Users/ugur/code/automating_tools/calibre"
kindle_drm_csv = "amazon_drm_books.csv"
csv_path = f"{data_dir}/{kindle_drm_csv}"


# I forgot to define this:
# content = ""
with open(csv_path, 'r', encoding='utf-8') as csv_file:
    # read whole content
    content = csv_file.read()

# why could I still print the content of the var?
# shouldn't it be undefined after leaving the `with` block?
print(content)

同样在这个例子中:

if 3<10:
    local_var = True
print(local_var) 
# prints True
# why?
# I left the if-then-block. 
# Shouldn't the local_var be undefined after leaving the block?

【问题讨论】:

  • @Philipp 非常棒。谢谢。但仍然:我的第二个例子无法用你的链接解释。
  • 我发送的线程中接受的答案的第一行指出,with、if、for 和 while 不要在 Python 中创建范围。这是否解释了您在第二个示例中的问题?
  • 是的。谢谢!

标签: python


【解决方案1】:

不是 C 中的 Python。C 自动变量确实是块范围的,但 Python 变量要么是全局的,要么是函数范围的 (*)。由于是同一个函数级别,块中声明的变量在块结束后仍然存在。


(*) 一个极端情况是理解被处理为 hidden 函数。因此,在推导中声明的变量将隐藏任何更高级别的同名范围变量,并将在推导之外消失

【讨论】:

    【解决方案2】:

    python中没有局部作用域(块作用域),只有函数作用域和全局作用域。

    【讨论】:

      【解决方案3】:

      在 Python 中,withif 不创建自己的范围。在您提供的代码中,contentlocal_var 是在全局范围内创建的,因此可以在 withif 语句之外访问。唯一创建自己作用域的 Python 构造是模块、类、函数、生成器表达式和 dict/set/list 推导式。

      【讨论】:

      • 那么在if 块或with 块中使用变量之前定义变量不是一个好习惯吗?
      猜你喜欢
      • 2019-07-04
      • 2015-09-30
      • 2019-06-01
      • 2013-11-06
      • 2016-11-13
      • 2017-03-05
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多