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...
伊谢尔伦2017-04-18 09:59:28
This is a bit like javascriptvar
in js
for(var i = 0; i < 100; i++){
//内容
}
console.log(i);//i = 100
Because the scope of variables defined in js var
定义的变量的作用域是整个函数,所以ES6语法中增加了一个let
,let
定义的变量就是块级作用域
如果是for(let i = 0; i < 100; i++)
,后面再log i的话就是undefined
is the entire function, so a let
is added to the ES6 syntax, and the variables defined by let
are block-level scope
for(let i = 0; i < 100; i++)
, if you log i later, it will be undefined
If it’s java, it’s also block-level scope
for(int i = 0; i < 100; i ++){
//i在块级作用域范围内
}
Your code is like java🎜怪我咯2017-04-18 09:59:28
You change it to this and print out the locals() function
def find(sequence, target):
for index, value in enumerate(sequence):
if value == target:
break
else:
return -1
print(locals())
return index
will find the output
{'index': 1, 'target': 1, 'value': 1, 'sequence': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
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__
PHP中文网2017-04-18 09:59:28
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