我在 Python 中有以下似乎有效的函数:
def test(self):
x = -1
# why don't I need to initialize y = 0 here?
if (x < 0):
y = 23
return y
但是为了让它工作,为什么我不需要初始化变量 y?我以为 Python 有 block 作用域,这怎么可能呢?
最佳答案
这似乎是对 scope in Python 的简单误解.条件语句不创建范围。名称 y
位于函数内部的局部范围内,因为语法树中存在以下语句:
y = 23
这是在函数定义时确定的,当函数被解析时。名称 y
可能在运行时未绑定(bind)时使用的事实无关紧要。
这是一个强调相同问题的更简单的示例:
>>> def foo():
... return y
... y = 23
...
>>> def bar():
... return y
...
>>> foo.func_code.co_varnames
('y',)
>>> bar.func_code.co_varnames
()
>>> foo()
# UnboundLocalError: local variable 'y' referenced before assignment
>>> bar()
# NameError: global name 'y' is not defined
关于python - Python如何打印超出范围的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39438573/