当我使用以下用户定义的异常时,我收到一条警告,即在Python 2.6中不推荐使用BaseException.message:
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
Run Code Online (Sandbox Code Playgroud)
这是警告:
DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
Run Code Online (Sandbox Code Playgroud)
这有什么问题?我需要更改什么来摆脱弃用警告?
我有一个shell脚本循环遍历包含URL的文本文件:我想访问并截取屏幕截图.
这一切都做得很简单.该脚本初始化一个类,该类在运行时创建列表中每个站点的屏幕截图.有些站点需要非常长的时间来加载,有些站点可能根本没有加载.所以我想将screengrabber-function包装在一个超时脚本中,False如果它在10秒内无法完成,则使函数返回.
我满足于最简单的解决方案,也许设置一个异步计时器,无论在函数内部实际发生什么,它将在10秒后返回False?
我通常会尝试确保我的对象实例符合Liskov替换原则,但我一直想知道人们是否认为LSP也应该适用于构造函数?
我已经尝试使用谷歌搜索,但无论如何我都无法找到任何强烈的意见.
我应该注意到我的大部分编码都是在Ruby中,但我有时会发现我的子类构造函数与父类略有不同.它们使用相同的基本参数集,通常是额外的参数.有时这也会发生在其他类方法中.
在我的脑后,这总是感觉像LSP违规,但我想看看是否有其他人也有这种感觉.
创建例外的最佳做法是什么?我刚看到这个,我不知道我是否应该感到恐惧或喜欢它.我在书中多次阅读异常永远不会持有字符串,因为字符串本身可以抛出异常.这有什么真相吗?
基本上我从脚本的理解是这样做,所以所有内部Python库将有一个共同的错误消息格式(迫切需要的东西)所以我可以理解为什么把错误消息字符串是一个好主意.(几乎每种方法都会抛出异常,因为完全不需要无效的通过).
有问题的代码如下:
"""
Base Exception, Error
"""
class Error(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "[ERROR] %s\n" % str(self.message)
def log(self):
ret = "%s" % str(self.message)
if(hasattr(self, "reason")):
return "".join([ret, "\n==> %s" % str(self.reason)])
return ret
class PCSException(Error):
def __init__(self, message, reason = None):
self.message = message
self.reason = reason
def __str__(self):
ret = "[PCS_ERROR] %s\n" % str(self.message)
if(self.reason != None):
ret += "[REASON] %s\n" % str(self.reason)
return ret
Run Code Online (Sandbox Code Playgroud)
这只是冰山一角,但有人可以给我一些洞察力,这是一个什么使这个可怕的想法?或者,如果有一个更好的异常编码过程/风格.
为什么下面的自定义Exception类没有使用pickle模块正确序列化/反序列化?
import pickle
class MyException(Exception):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
super(MyException, self).__init__(arg1)
e = MyException("foo", "bar")
str = pickle.dumps(e)
obj = pickle.loads(str)
Run Code Online (Sandbox Code Playgroud)
此代码抛出以下错误:
Traceback (most recent call last):
File "test.py", line 13, in <module>
obj = pickle.loads(str)
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1133, in load_reduce
value = func(*args)
TypeError: __init__() takes exactly 3 arguments (2 given)
Run Code Online (Sandbox Code Playgroud)
我敢肯定这个问题源于我对如何使课堂泡菜友好缺乏了解.有趣的是,当我的类没有扩展Exception时,不会发生这个问题.
谢谢你的帮助.凯尔
编辑:修复我的超级shx2编辑编辑:清理标题/内容
现在我只有一个空白的异常类.我想知道如何在它被引发时给它一个变量,然后当我在try中处理它时检索该变量...除外.
class ExampleException (Exception):
pass
Run Code Online (Sandbox Code Playgroud) 考虑
try:
import someProprietaryModule
except ImportError:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
Run Code Online (Sandbox Code Playgroud)
运行时,如果未安装someProprietaryModule,则可以看到:
(traceback data)
ImportError: unknown module: someProprietaryModule
During handling of the above exception, another exception occurred:
(traceback data)
ImportError: It appears that <someProprietaryModule> is not installed...
Run Code Online (Sandbox Code Playgroud)
也许我不希望出现"在处理上述异常......"行(以及它上面的行).我能做到这一点:
_moduleInstalled = True
try:
import someProprietaryModule
except ImportError:
_moduleInstalled = False
if not _moduleInstalled:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
Run Code Online (Sandbox Code Playgroud)
但这感觉有点像黑客.我还能做什么?
我想在Python中创建一个自定义异常,当没有任何参数引发时,它将打印一个默认消息.
案例:
>>> class CustomException(Exception):
# some code here
>>> raise CustomException
Run Code Online (Sandbox Code Playgroud)
并获得以下输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
Run Code Online (Sandbox Code Playgroud) 这样安全吗?
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”,然后从处理程序中的错误中获取详细信息)
如果没有覆盖“消息”,我有一个基本的检查,是否也应该跳过对自己设置其他属性?这些是什么?
python ×9
exception ×8
class-method ×1
constructor ×1
deprecated ×1
liskov-substitution-principle ×1
python-3.3 ×1
python-3.x ×1
traceback ×1