如何重现这个警告
让我澄清一下问题,由于在问题的示例代码中无法重现此问题,因此如果您已经打开了警告(通过-W
标志、PYTHONWARNINGS
环境变量或warnings 模块),则可以在 Python 2.6 和 2.7 中重现此警告:
>>> error = Exception('foobarbaz')
>>> error.message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foobarbaz'
停止使用.message
我更喜欢使用repr(error)
,它返回一个包含错误类型名称、消息的repr(如果有),以及其余参数的repr的字符串。
>>> repr(error)
"Exception('foobarbaz',)"
在仍使用.message
的情况下消除警告
而消除DeprecationWarning
的方法是按照Python设计师的意图,子类化一个内置异常:
class MyException(Exception):
def __init__(self, message, *args):
self.message = message
# delegate the rest of initialization to parent
super(MyException, self).__init__(message, *args)
>>> myexception = MyException('my message')
>>> myexception.message
'my message'
>>> str(myexception)
'my message'
>>> repr(myexception)
"MyException('my message',)"
仅获取.message
属性,而不是error.message
如果您知道异常只有一个参数——即一个消息,并且这正是您想要的,最好避免使用消息属性,而是直接获取错误的str
。例如,对于一个子类化的Exception
:
class MyException(Exception):
'''demo straight subclass'''
并且用法:
>>> myexception = MyException('my message')
>>> str(myexception)
'my message'
请参见此答案:
Proper way to declare custom exceptions in modern Python?