Python的变量作用域和java,C,C#有很大不同,比如以下代码,在Python中执行是没有问题的:
if __name__ == '__main__':
for i in range(5):
test = i
print '%d' % test
Python 2.2中,Python正式引入了一种新的作用域 --- 嵌套作用域。
Python查找变量的顺序是:LEGB(L:Local,E:Enclosing,G:Global,B:Built-in)
测了下JavaScript,发现和Python一样具有相同的变量查找顺序:
if (true) {
var test = 'zsd';
}
console.log(test);
这样运行也不会报错,输出zsd
,这样换做C、Java或C#早就报错了。
以前还真没有注意过嵌套作用域,感觉这种代码怪怪的,容易出问题。
Related Issues not found
Please contact @stanzhai to initialize the comment