Python:如果在 try 或 if 中定义,变量仍然可以访问? [英] Python: Variables are still accessible if defined in try or if?

查看:74
本文介绍了Python:如果在 try 或 if 中定义,变量仍然可以访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 初学者,来自 C/C++ 背景.我使用的是 Python 2.7.

I'm a Python beginner and I am from C/C++ background. I'm using Python 2.7.

我阅读了这篇文章:A Beginner's Guide to Python's Namespaces, Scope Resolution, and the LEGB Rule,我想我对 Python 的这些技术有一些了解.

I read this article: A Beginner’s Guide to Python’s Namespaces, Scope Resolution, and the LEGB Rule, and I think I have some understanding of Python's these technologies.

今天我意识到我可以像这样编写 Python 代码:

Today I realized that I can write Python code like this:

if condition_1:
    var_x = some_value
else:
    var_x = another_value
print var_x

也就是说,var_x 仍然可以访问,即使它定义 before if.因为我来自 C/C++ 背景,这对我来说是新的东西,就像在 C/C++ 中一样,var_x 被定义在 if 和 else 包围的范围内,因此除非你在 if 之前定义 var_x.

That is, var_x is still accessible even it is not define before the if. Because I am from C/C++ background, this is something new to me, as in C/C++, var_x are defined in the scope enclosed by if and else, therefore you cannot access it any more unless you define var_x before if.

我尝试在 Google 上搜索答案,但因为我对 Python 还是个新手,我什至不知道从哪里开始以及应该使用哪些关键字.

I've tried to search the answers on Google but because I'm still new to Python, I don't even know where to start and what keywords I should use.

我的猜测是,在 Python 中,if 不会创建新的作用域.if 中新定义的所有变量都在 if 所在的范围内,这就是为什么在 if 之后仍然可以访问该变量的原因>.但是,如果 var_x,在上面的例子中,只定义在 if 而不是在 else 中,将发出警告说print var_x 可能引用未定义的变量.

My guess is that, in Python, if does not create new scope. All the variables that are newly defined in if are just in the scope that if resides in and this is why the variable is still accessible after the if. However, if var_x, in the example above, is only defined in if but not in else, a warning will be issued to say that the print var_x may reference to a variable that may not be defined.

我对自己的理解有些信心.但是,如果我在某处错了,有人可以帮助纠正我,或者给我一个讨论此问题的文档的链接吗??

I have some confidence in my own understanding. However, could somebody help correct me if I'm wrong somewhere, or give me a link of the document that discusses about this??

谢谢.

推荐答案

我的猜测是,在 Python 中,if 不会创建新的作用域.if 中新定义的所有变量都在 if 所在的范围内,这就是为什么在 if 之后仍然可以访问该变量的原因.

My guess is that, in Python, if does not create new scope. All the variables that are newly defined in if are just in the scope that if resides in and this is why the variable is still accessible after the if.

没错.在 Python 中,命名空间,基本上决定了关于变量范围,只为模块和函数(包括方法;基本上是任何 def)创建.因此,在一个函数中(而不是在子函数中)发生的所有事情都放在同一个命名空间中.

That is correct. In Python, namespaces, that essentially decide about the variable scopes, are only created for modules, and functions (including methods; basically any def). So everything that happens within a function (and not in a sub-function) is placed in the same namespace.

然而,重要的是要知道,仅仅在函数中存在赋值就会在本地命名空间中保留一个名称.这导致了一些有趣的情况:

It’s important to know however that the mere existance of an assignment within a function will reserve a name in the local namespace. This makes for some interesting situations:

def outer ():
    x = 5
    def inner ():
        print(x)
        # x = 10
    inner()
outer()

在上面的代码中,注释掉该行后,代码将打印 5,如您所料.这是因为 inner 将在外部范围内查找名称 x.但是,如果添加行 x = 10,名称 xlocalinner,因此 earlier 查找 x 将在 inner 的本地命名空间中查找.但是由于它还没有被赋值,你会收到一个UnboundLocalError(赋值前引用的局部变量'x'").nonlocal 语句被添加到 Python 3 中,以解决一个问题:想要在内部函数中实际修改外部作用域的 x 的情况.

In the code above, with that line commented out, the code will print 5 as you may expect. That’s because inner will look in the outer scope for the name x. If you add the line x = 10 though, the name x will be local to inner, so the earlier look up to x will look in the local namespace of inner. But since it hasn’t been assigned yet, you will receive an UnboundLocalError ("local variable 'x' referenced before assignment"). The nonlocal statement was added in Python 3 to overcome one issue from this: The situation where you want to actually modify the x of the outer scope within the inner function.

有关名称查找的更多信息,请参阅此相关问题.

For more information on name lookup, see this related question.

这篇关于Python:如果在 try 或 if 中定义,变量仍然可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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