search

Home  >  Q&A  >  body text

python - for...in 中的局部变量, 为何能在外面使用?

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

怪我咯怪我咯2884 days ago1446

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦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语法中增加了一个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🎜

    reply
    0
  • 怪我咯

    怪我咯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

    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__

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:59:28

    Python has no block scope

    The smallest range is function

    reply
    0
  • PHP中文网

    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

    reply
    0
  • Cancelreply