【发布时间】:2021-06-22 03:05:58
【问题描述】:
您可能知道,变量的范围在 python (What are the rules for local and global variables in Python?) 中是静态确定的。
例如:
a = "global"
def function():
print(a)
a = "local"
function()
# UnboundLocalError: local variable 'a' referenced before assignment
同样的规则适用于类,但它似乎默认为全局范围,而不是引发AttributeError:
a = "global"
class C():
print(a)
a = "local"
# 'global'
此外,在嵌套函数的情况下,行为是相同的(不使用nonlocal 或global):
a = "global"
def outer_func():
a = "outer"
def inner_func():
print(a)
a = "local"
inner_func()
outer_func()
# UnboundLocalError: local variable 'a' referenced before assignment
但在嵌套类的情况下,它仍然默认为全局范围,而不是外部范围(同样不使用global 或nonlocal):
a = "global"
def outer_func():
a = "outer"
class InnerClass:
print(a)
a = "local"
outer_func()
# 'global'
最奇怪的是,当没有a 的声明时,嵌套类默认为外部作用域:
a = "global"
def outer_func():
a = "outer"
class InnerClass:
print(a)
outer_func()
# 'outer'
所以我的问题是:
- 为什么函数和类之间存在差异(一个引发异常,另一个默认为全局范围。
- 在嵌套类中,为什么在使用之后定义的变量时,默认范围必须变为全局范围,而不是继续使用外部范围?
【问题讨论】:
-
这几乎就是它应该表现的样子。你读过哪些文档?
标签: python python-3.x