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,…
- Python填坑记——作用域
- python——作用域
- Python——作用域
- Python——作用域基础
- day10——Python作用域
- Python学习笔记——作用域
- python参数—星号作用
- python——作用域 == is
- python 变量作用域
- python 变量作用域
- python变量作用域
- python作用域
- python 变量作用域
- python 变量作用域
- python变量作用域
- python 变量作用域
- python变量作用域
- python的作用域
- 为VS2010添加背景图
- 幂律分布与自组织过程
- Arduino接口-week2-Lesson3
- poj-1260 -Pearls-DP
- linux下C 信号集处理函数
- Python填坑记——作用域
- Java设计模式之单例模式
- spring的CORS
- FragmentTabHost使用方法
- C++/C面试题集
- hadoop FS Shell
- Swift利用闭包反向传值
- 集合初探(二)
- 河内之塔(汉诺塔) java实现