首页 > Python基础教程 >
-
Python 程序员经常犯的 10 个错误(6)
在Python 2中运行正常:
$ python foo.py 1
key error
1
$ python foo.py 2
value error
2
但是,现在让我们把它在Python 3中运行一下:
$ python3 foo.py 1
key error
Traceback (most recent call last):
File "foo.py", line 19, in <module>
bad()
File "foo.py", line 17, in bad
print(e)
UnboundLocalError: local variable 'e' referenced before assignment
出什么问题了? “问题”就是,在 Python 3 中,异常的对象在 except 代码块之外是不可见的。(这样做的原因是,它将保存一个对内存中堆栈帧的引用周期,直到垃圾回收器运行并且从内存中清除掉引用。了解更多技术细节请参考这里) 。
一种解决办法是在 except 代码块的外部作用域中定义一个对异常对象的引用,以便访问。下面的例子使用了该方法,因此最后的代码可以在Python 2 和 Python 3中运行良好。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import sys def bar(i): if i = = 1 : raise KeyError( 1 ) if i = = 2 : raise ValueError( 2 ) def good(): exception = None try : bar( int (sys.argv[ 1 ])) except KeyError as e: exception = e print ( 'key error' ) except ValueError as e: exception = e print ( 'value error' ) print (exception) good() |
在Py3k中运行:
$ python3 foo.py 1
key error
1
$ python3 foo.py 2
value error
2
正常!
(顺便提一下, 我们的 Python Hiring Guide 讨论了当我们把代码从Python 2 迁移到 Python 3时的其他一些需要知道的重要差异。)
常见错误 10: 误用__del__方法
假设你有一个名为 calledmod.py 的文件:
1
2
3
4
5
|
import foo class Bar( object ): ... def __del__( self ): foo.cleanup( self .myhandle) |