Alm*_*mad 4 python grammar parsing scope
这需要我深入挖掘Python资源,但由于SO上有很多人已经这样做了,我很想听听他们的指示.
>>> import os
>>> def scope():
... print os
... import os
...
>>> scope()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in scope
UnboundLocalError: local variable 'os' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
在我看来,当解析器解释文件时,它会自动为范围函数创建局部范围,这使得os从全局范围"分离".
这是真的吗?有人关心我在哪里可以找到有关范围实施的更多信息吗?
编辑:此外,这不是导入的特殊情况,这也适用于通常的变量.
当你调用scope()Python时,你会看到你的方法中有一个名为osused 的局部变量(从import里面开始scope),所以这会掩盖全局变量os.但是,当您说print os您尚未到达该行并执行本地导入时,您会在分配之前看到有关参考的错误.以下是其他一些可能有用的示例:
>>> x = 3
>>> def printx():
... print x # will print the global x
...
>>> def printx2():
... print x # will try to print the local x
... x = 4
...
>>> printx()
3
>>> printx2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in printx2
UnboundLocalError: local variable 'x' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
回到你的os榜样.任何赋值都os具有相同的效果:
>>> os
<module 'os' from 'C:\CDL_INSTALL\install\Python26\lib\os.pyc'>
>>> def bad_os():
... print os
... os = "assigning a string to local os"
...
>>> bad_os()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bad_os
UnboundLocalError: local variable 'os' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
最后,比较这两个例子:
>>> def example1():
... print never_used # will be interpreted as a global
...
>>> def example2():
... print used_later # will be interpreted as the local assigned later
... used_later = 42
...
>>> example1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example1
NameError: global name 'never_used' is not defined
>>> example2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example2
UnboundLocalError: local variable 'used_later' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1541 次 |
| 最近记录: |