[英]What is the reason for initializing self.args when you do class MyException(Exception)?
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')
Beazley: pg 88 比兹利:第88页
"it is important to assign a tuple containing the arguments to _ init _() to the attribute self.args as shown.This attribute is used when printing exception traceback messages. If you leave it undefined, users won't be able to see any useful information about the exception when an error occurs."
“重要的是,如图所示,将包含_ init _()参数的元组分配给属性self.args。此属性在打印异常回溯消息时使用。如果未定义,则用户将看不到发生错误时有关异常的任何有用信息。”
If i do: 如果我做:
try:
....
except DeviceError:
....
here self.args is not used since a Traceback is not generated - Correct? 此处未使用self.args,因为未生成回溯-是吗? if i ignore DeviceError for some reason, then the sys.excepthook() function that is called will need to print a Traceback and will look in self.args - correct?
如果由于某种原因我忽略了DeviceError ,则被调用的sys.excepthook()函数将需要打印一个Traceback,并将查找self.args-对吗? What does it look for?
它寻找什么? I mean I'm just stuffing random values in a tuple.. how does the default error handler(excepthook function) know how to display errno and msg?
我的意思是我只是将随机值填充到元组中。默认错误处理程序(excepthook函数)如何知道如何显示errno和msg?
Could someone explain what exactly goes on with self.args and is it used in Python 3.x? 有人可以解释self.args到底发生了什么,并且在Python 3.x中使用了它吗?
args
is used in the __str__
and __repr__
of the base Exception
type. args
用于基本Exception
类型的__str__
和__repr__
中。 Translating from the C source, these are roughly as follows: 从C源代码进行转换,大致如下:
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)
You don't need to set args
, but it means you don't need to write your own __str__
or __repr__
. 您不需要设置
args
,但这意味着您不需要编写自己的__str__
或__repr__
。
Also, rather than setting args
yourself you should pass it to the parent constructor: 另外,除了自己设置
args
还应该将其传递给父构造函数:
class DeviceError(Exception):
def __init__(self, errno, msg):
super(DeviceError, self).__init__(errno, msg)
self.errno = errno
self.errmsg = msg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.