Python except语法误解

under python

in tech

Published: 2016-10-14

Python里很多情况下a, b, c等价于(a, b, c),比如表示和分解tuple,以下四种写法等价:

a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2
(a, b) = (1, 2)

from ... import ...语句中:

from os import chmod, chown
from os import (unlink, rmdir)

except子句确实是个例外,except a, b的意思是except a as b,是为了向后兼容而保留的语法,这种语法已被Python 3禁用,如果想在一个子句里捕获两类异常,应该写成except (a, b)

如果不小心遗忘了括号,可能会引起莫名奇妙的错误,如果用Python 2运行下面这段代码:

class ErrorA(Exception):
    pass

class ErrorB(Exception):
    pass

try:
    raise ErrorA()
except ErrorA, ErrorB:
    print("Caught ErrorA or ErrorB")

try:
    raise ErrorB()
except ErrorB:
    print("Caught ErrorB")

会被提示TypeError: 'ErrorA' object is not callable,因为ErrorBErrorA的实例对象覆盖了。

(完)