python - Python如何打印超出范围的变量

标签 python block

我在 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/

相关文章:

python - 在python中用父类方法覆盖__init__

ios - 最后一个 block 返回时触发方法

swift - SpriteKit SKAction.runBlock 传递参数问题

php - 如何检查字符串是否包含 zalgo 文本?

python - Flask 不会在 html 中播放视频

python - 在 Python 中使用数据类方法定义属性

python - 使用至少 n 个空格拆分字符串

python - 查找轮廓和边界以获取图像内部的点 OpenCV Python

ios - UIKit Dynamics/Blocks - 完成时删除 UIPushBehavior

latex - 在 Latex 文档中插入内联代码块