Python如何打印超出范围的变量 [英] How does Python print a variable that is out of scope

查看:131
本文介绍了Python如何打印超出范围的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中具有以下似乎正常的功能:

I have the following function in Python that seems to be working:

def test(self):
    x = -1
    # why don't I need to initialize y = 0 here?
    if (x < 0):
        y = 23

    return y

但是要执行此操作,为什么我不需要初始化变量y?我以为Python有块作用域,那怎么可能呢?

But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible?

推荐答案

这似乎是对 Python中的作用域的简单误解.条件语句不会创建作用域.名称y在函数内部的本地范围内,因为语法树中存在以下语句:

This appears to be a simple misunderstanding about scope in Python. Conditional statements don't create a scope. The name y is in the local scope inside the function, because of this statement which is present in the syntax tree:

y = 23

这是在解析函数时在函数定义时确定的.名称y可以在运行时未绑定时使用,这一事实是无关紧要的.

This is determined at function definition time, when the function is parsed. The fact that the name y might be used whilst unbound at runtime is irrelevant.

这是一个更简单的示例,突出了相同的问题:

Here's a simpler example highlighting the same issue:

>>> 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如何打印超出范围的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆