![](/img/trans.png)
[英]Decorator to automate "for arg in self.args" process in class methods
[英]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')
比兹利:第88页
“重要的是,如图所示,将包含_ init _()参数的元组分配给属性self.args。此属性在打印异常回溯消息时使用。如果未定义,则用户将看不到发生错误时有关异常的任何有用信息。”
如果我做:
try:
....
except DeviceError:
....
此处未使用self.args,因为未生成回溯-是吗? 如果由于某种原因我忽略了DeviceError ,则被调用的sys.excepthook()函数将需要打印一个Traceback,并将查找self.args-对吗? 它寻找什么? 我的意思是我只是将随机值填充到元组中。默认错误处理程序(excepthook函数)如何知道如何显示errno和msg?
有人可以解释self.args到底发生了什么,并且在Python 3.x中使用了它吗?
args
用于基本Exception
类型的__str__
和__repr__
中。 从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)
您不需要设置args
,但这意味着您不需要编写自己的__str__
或__repr__
。
另外,除了自己设置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.