Python填坑记——作用域

来源:互联网 发布:淘宝直通车黑车 编辑:程序博客网 时间:2024/05/17 03:43

先来看看两段代码:

def fn():    if True:        week = {'monday' : 1}    week.update({'tuesday' : 2})    for (k , v) in week.items():        print k,vdef fn_1(var):    for var in [0,1,2]:        var += 1    print varfn()fn_1(var=10)

想必大家都有C语言基础,如果第一眼看到这样的python代码,会有这样的疑问:
1. fn()中,为什么week超出if代码块,还没有报错
2. fn_1(var=10) 输出结果为什么是3

其实,在python中只有三种作用域:(以下引用自Naming and binding)

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
Python lacks declarations and allows name binding operations to occur anywhere within a code block.

也就是说Python中的变量可以分别在def/lambda,class,module的作用域下的任意位置生效,而不需要声明。 这也就是为什么以上代码片的结果出人意料。

进一步理解,在python中,如何区分不同作用域下的变量?(以下引用自 What are the rules for local and global variables in Python )

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

如果还没有完全理解,可以参考下LEGB Rule

L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.

E, Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G, Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.

B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,…

0 0
原创粉丝点击