警告を再現する方法
質問のサンプル コードでこれを再現できないため、問題を明確にさせてください。( -W
flag、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
Exception への 1 つの引数 (メッセージ) があり、それが必要であることがわかっている場合は、メッセージ属性を避けてstr
エラーの を取得することをお勧めします。サブクラス化された について言うException
:
class MyException(Exception):
'''demo straight subclass'''
そして使用法:
>>> myexception = MyException('my message')
>>> str(myexception)
'my message'
この回答も参照してください。
最新のPythonでカスタム例外を宣言する適切な方法は?