python - for...in 中的局部变量, 为何能在外面使用?
怪我咯
怪我咯 2017-04-18 09:57:28
0
4
1359

2016/11/20

问题

详情见代码

Python 作为高级语言, 抽象层次很高, 然一个程序员一般都会好几门语言, 有时候会在语言的细节处, 发生概念性的混淆

  1. 有点害怕, 是不是一直误解了 Python 的作用域原理?

  2. 正确的作用域原理是什么?

答案: 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 中

重现

  1. 拷贝代码, 运行

尝试解决

  1. 搜索了 Python 作用域的相关介绍

  2. https://www.zhihu.com/questio...

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
伊谢尔伦

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语法中增加了一个letlet定义的变量就是块级作用域
如果是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

If it is 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🎜
刘奇

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

  1. Search at the innermost level, usually in a function, locals()

  2. Search within the module, i.e. globals()

  3. 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!