BaseException.message は Python 2.6 で非推奨になりました 質問する

BaseException.message は Python 2.6 で非推奨になりました 質問する

次のユーザー定義の例外を使用すると、BaseException.message は Python 2.6 では非推奨であるという警告が表示されます。

class MyException(Exception):

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return repr(self.message)

これは警告です:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message

これの何が問題なのでしょうか? 非推奨の警告を消すには何を変更する必要がありますか?

ベストアンサー1

ソリューション - コーディングはほとんど不要

例外クラスを継承しException、メッセージをコンストラクタの最初のパラメータとして渡すだけです。

例:

class MyException(Exception):
    """My documentation"""

try:
    raise MyException('my detailed description')
except MyException as my:
    print my # outputs 'my detailed description'

str(my)または (あまりエレガントではありませんが)を使用しmy.args[0]てカスタム メッセージにアクセスできます。

背景

Pythonの新しいバージョン(2.6以降)では、Exceptionからカスタム例外クラスを継承することになっています(Python 2.5から) は BaseException を継承しています。背景については、ペップ352

class BaseException(object):

    """Superclass representing the base of the exception hierarchy.
    Provides an 'args' attribute that contains all arguments passed
    to the constructor.  Suggested practice, though, is that only a
    single string argument be passed to the constructor."""

__str__これらは__repr__、特に引数が 1 つだけの場合 (メッセージとして使用できる) には、すでに意味のある方法で実装されています。

他の人の提案に従って繰り返したり__str____init__実装したり、作成したりする必要はありません。_get_message

おすすめ記事