为什么python对范围不严格?

时间:2015-11-03 07:13:30

标签: python

python中的范围共享如何工作?:

def test():
    if True:
        a = 3
    print a

这个问题已经有好几种方式被问到了,但是问题是什么,python对范围不是那么严格? C ++中的相同代码会产生错误:

error: 'a' was not declared in this scope

2 个答案:

答案 0 :(得分:2)

在C ++中,每组括号都定义了一个新的范围,但对于Python和缩进级别则不然。在Python中只有函数和模块定义范围;像if这样的控制块没有。

答案 1 :(得分:2)

Python的范围共享规则背后的原因是Python选择不对局部变量进行显式声明。如果没有这样的声明,C ++样式的作用域规则,每个嵌套创建一个新的作用域将导致以下失败:

def test():
    if some_condition:
        a = 3
    else:
        a = 5
    # If the above nesting created a new scope, "a" would
    # now be out of scope.
    print a

这适用于C ++,因为显式声明为您提供了写作之间的选择:

// doesn't work
if (some_condition) {
    int a = 3;
}
else {
    int a = 5;
}
// "a" is out of scope
std::cout << a ;

// works
int a;
if (some_condition) {
    a = 3;
}
else {
    a = 5;
}
printf("%d\n", a);

Python,没有对局部变量的显式声明,必须将范围扩展到整个函数定义(以及类范围的类定义)。