2016/11/20
详情见代码
Python 作为高级语言, 抽象层次很高, 然一个程序员一般都会好几门语言, 有时候会在语言的细节处, 发生概念性的混淆
有点害怕, 是不是一直误解了 Python 的作用域原理?
正确的作用域原理是什么?
答案: LEGB法则
初学 Python 语法的时候, 由于觉得这东西太复杂, 就快速跳过了, 没想到是个坑( maybe feature ? )
def find(sequence, target):
for index, value in enumerate(sequence):
if value == target:
break
else:
return -1
return index # ?? 这里是否可表示 index 已经逃离 for...in 作用域了?
print find(range(10), 1)
for iii in range(10):
iii += 1
print iii
一直以为是这样的
for (int i=0; i<10; ++i)
do something # i的作用域在 for 中
拷贝代码, 运行
搜索了 Python 作用域的相关介绍
https://www.zhihu.com/questio...
This is a bit like javascript
var
in js
Because the scope of variables defined in js
If it isvar
定义的变量的作用域是整个函数,所以ES6语法中增加了一个let
,let
定义的变量就是块级作用域如果是
for(let i = 0; i < 100; i++)
,后面再log i的话就是undefined
is the entire function, so alet
is added to the ES6 syntax, and the variables defined bylet
are block-level scopefor(let i = 0; i < 100; i++)
, if you log i later, it will beundefined
You change it to this and print out the locals() function
will find the output
You can see from the output that index, value, target, and sequence are in the same namespace. Because they are both in the same function. So you can access the index.
Scope of python
Search at the innermost level, usually in a function, locals()
Search within the module, i.e. globals()
Search outside the module, that is, search in __builtin__
Python has no block scope
The smallest range is function
Simply put, in python only modules, classes, and functions will create new scopes, so the variables defined in the for loop can also be accessed outside the loop, as long as they are in the same scope