这样安全吗?
class SpecialAlert(Exception):
def __init__(self, message, **kwargs):
Exception.__init__(self, message)
for kw in kwargs:
if kw == 'message':
continue
setattr(self, kw, kwargs[kw])
Run Code Online (Sandbox Code Playgroud)
屁股..这安全吗?我的意思是我要超越自我的属性?
在SpecialAlert中,我想传递所有类型的内容(这是一连串的不同检查的例外,我在循环中执行“ try..except SpecialAlert as error”,然后从处理程序中的错误中获取详细信息)
如果没有覆盖“消息”,我有一个基本的检查,是否也应该跳过对自己设置其他属性?这些是什么?
这样可以正常工作;在对象上添加其他属性是非常繁琐的。但是,与其专门检查标准属性,还不如不想破坏,只需调用Exception.__init__last,然后在不小心设置它们的情况下让它破坏您的属性。然后,您__init__()可以是:
def __init__(self, message, **kwargs):
self.__dict__.update(kwargs)
Exception.__init__(self, message)
Run Code Online (Sandbox Code Playgroud)