Python填坑记——作用域

先来看看两段代码:

def fn():
    if True:
        week = {'monday' : 1}
    week.update({'tuesday' : 2})
    for (k , v) in week.items():
        print k,v

def fn_1(var):
    for var in [0,1,2]:
        var += 1
    print var

fn()
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,…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值