简体   繁体   English

为什么Python让我在一个范围内定义变量,但在另一个范围内使用它?

[英]Why does Python let me define a variable in one scope, but use it in another?

I see that it's possible to define a variable inside a scope, but then refer to it outside that scope. 我看到可以在范围内定义一个变量,但是然后在该范围之外引用它。 For instance, the following code works: 例如,以下代码有效:

if condition:
    x = 5
else:
    x = 10
print x

However, this strikes me as a bit weird. 然而,这让我觉得有些奇怪。 If you tried to do this in C, the variable X would not be scoped properly: 如果您尝试在C中执行此操作,则变量X将无法正确确定范围:

if(condition) { int x = 5; }
else { int x = 10; }
print x; // Doesn't work: x is unavailable!

The solution, in C anyway, is to declare X first, THEN figure out what do to with it: 无论如何,在C中的解决方案是首先声明X,然后找出它的作用:

int x;
if(condition) { x = 5; }
else { x = 10; }
print x; // Works!

So, in Python, my instinct is to write code like this: 所以,在Python中,我的直觉就是编写如下代码:

x = None
if condition:
    x = 5
else:
    x = 10
print x

However, I realize Python doesn't require me to do this. 但是,我意识到Python并不要求我这样做。 Any suggestions? 有什么建议? Is there a style guideline for this scenario? 这种情况是否有样式指南?

Blocks do not create a new scope in Python. 块不会在Python中创建新范围。 Modules, classes, and functions do. 模块,类和函数都可以。

Also: 也:

x = 10
if condition:
    x = 5
print x

or: 要么:

x = 5
if not condition:
    x = 10
print x

My suggestion: 我的建议:

Write Python, not C. 写Python,而不是C.

In Python we use blocks. 在Python中我们使用块。 An if is a block. if是一个块。 A block doesn't necessarily mean a different scope in Python. 块不一定意味着Python中的不同范围。

In your example, you might try this: 在您的示例中,您可以尝试这样做:

x = 10
if condiiton:
    x = 5
print x

As for why Python doesn't have the same scoping rules as C (and C++ and Java), the short answer is that they're different languages. 至于为什么Python没有与C(和C ++和Java)相同的范围规则,简短的答案是它们是不同的语言。 The long answer has to do with efficiency. 长期答案与效率有关。 In C, these scoping rules are all handled at compile time, there's no runtime overhead. 在C中,这些作用域规则都是在编译时处理的,没有运行时开销。 In Python, it would have to store an inner scope in a new dict , and that would add overhead. 在Python中,它必须在新的dict存储内部作用域,这会增加开销。 I'm sure there are other reasons, but this is a big practical one. 我确定还有其他原因,但这是一个很实用的原因。

You're not creating a new scope, so there's no scoping problem. 您没有创建新范围,因此没有范围问题。

However, note that if you do something like: 但请注意,如果您执行以下操作:

if foo:
    x = 10
print x

You'll get a NameError raised if foo is False, so you might come across a case where you actually do want to define your variable outside of the conditional (or add an else to assign it None .) 你会得到,如果NameError提出foo是假,所以你可能会遇到在那里你其实想定义变量条件之外的情况下(或添加else指定其None 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM