1
class DeviceError(Exception):
    def __init__(self,errno,msg):
        self.args = (errno, msg)
        self.errno = errno
        self.errmsg = msg

# Raises an exception (multiple arguments)
raise DeviceError(1, 'Not Responding')

比兹利:第 88 页

“将包含 _ init _() 参数的元组分配给属性 self.args 很重要,如图所示。此属性用于打印异常回溯消息。如果未定义,用户将无法看到发生错误时有关异常的任何有用信息。”

如果我做:

try:
 ....
except DeviceError:
 ....

这里self.args没有使用,因为没有生成 Traceback - 对吗?如果我出于某种原因忽略了 DeviceError,那么被调用的sys.excepthook()函数将需要打印一个 Traceback 并且会查看 self.args - 对吗?它在寻找什么?我的意思是我只是在一个元组中填充随机值。默认错误处理程序(excepthook 函数)如何知道如何显示 errno 和 msg?

有人可以解释一下 self.args 到底发生了什么,它在 Python 3.x 中使用了吗?

4

1 回答 1

1

args用于基本类型的__str__and中。从C源翻译过来,大致如下:__repr__Exception

def __str__(self):
    return ("" if len(self.args) == 0 else
            str(self.args[0]) if len(self.args) == 1 else
            str(self.args))

def __repr__(self):
    return "%s%r" % (self.__class__.__name__.split('.')[-1], self.args)

不需要设置args,但这意味着您不需要编写自己的__str__or __repr__

此外,与其设置args自己,不如将其传递给父构造函数:

class DeviceError(Exception):
    def __init__(self, errno, msg):
        super(DeviceError, self).__init__(errno, msg)
        self.errno = errno
        self.errmsg = msg
于 2013-08-02T08:40:20.723 回答