ホームページ  >  記事  >  バックエンド開発  >  Pythonの二項算術演算を詳しく解説

Pythonの二項算術演算を詳しく解説

coldplay.xixi
coldplay.xixi転載
2020-09-10 16:41:212441ブラウズ

Pythonの二項算術演算を詳しく解説

関連する学習の推奨事項: python チュートリアル

属性アクセスの解釈に関する私のブログ投稿に誰もが熱心に反応し、これにインスピレーションを与えました。 Python の構文のどのくらいが実際に単なる構文糖であるかについては、別の記事を書く予定です。この記事では、二項算術演算について説明したいと思います。

具体的には、引き算の仕組み a - b について説明したいと思います。減算は可換ではないので、意図的に減算を選択しました。これは、実装中に誤って a と b を入れ替えても同じ結果が得られる可能性がある加算演算と比較して、演算の順序の重要性を強調しています。

C コードの表示

いつものように、CPython インタープリターによってコンパイルされたバイトコードを確認することから始めます。

>>> def sub(): a - b... >>> import dis>>> dis.dis(sub)  1           0 LOAD_GLOBAL              0 (a)              2 LOAD_GLOBAL              1 (b)              4 BINARY_SUBTRACT              6 POP_TOP              8 LOAD_CONST               0 (None)             10 RETURN_VALUE复制代码

BINARY_SUBTRACT オペコードを詳しく調べる必要があるようです。 Python/ceval.c ファイルを確認すると、このオペコードを実装する C コードが次のとおりであることがわかります:

case TARGET(BINARY_SUBTRACT): {
    PyObject *right = POP();
    PyObject *left = TOP();
    PyObject *diff = PyNumber_Subtract(left, right);
    Py_DECREF(right);
    Py_DECREF(left);
    SET_TOP(diff);    if (diff == NULL)    goto error;
    DISPATCH();
}复制代码

出典: github.com/python/cpyt…

キー コードこれは PyNumber_Subtract () で、減算の実際のセマンティクスを実装します。引き続きこの関数のマクロをいくつか見てみると、binary_op1() 関数が見つかります。これは、バイナリ操作を管理するための一般的な方法を提供します。

ただし、実装のリファレンスとしては使用せず、Python データ モデルを使用します。公式ドキュメントは非常に優れており、減算で使用されるセマンティクスが明確に紹介されています。

データ モデルから学ぶ

データ モデルのドキュメントをよく読むと、減算の実装に重要な役割を果たす 2 つのメソッド (__sub__ と __rsub__) があることがわかります。

1. __sub__() メソッド

a - b を実行すると、a の型に __sub__() が見つかり、b がその型として使用されます。パラメータ。これは、属性アクセスに関する私の記事の __getattribute__() によく似ており、特殊/マジック メソッドは、パフォーマンスを目的としてオブジェクト自体ではなく、オブジェクトのタイプに基づいて解析されます。以下のコード例では、_ mro_getattr() を使用しています。このプロセス。

したがって、__sub__() が定義されている場合、type(a).__sub__(a,b) が減算に使用されます。 (注釈: マジック メソッドは、オブジェクトではなく、オブジェクトの型に属します)

これは、本質的に、減算は単なるメソッド呼び出しであることを意味します。標準ライブラリのoperator.sub()関数と考えることもできます。

この関数を模倣して独自のモデルを実装します。サンプル コードを理解しやすくするために、それぞれ a-b の左側と右側を表す 2 つの名前 lhs と rhs を使用します。

# 通过调用__sub__()实现减法 def sub(lhs: Any, rhs: Any, /) -> Any:
    """Implement the binary operation `a - b`."""
    lhs_type = type(lhs)    try:
        subtract = _mro_getattr(lhs_type, "__sub__")    except AttributeError:
        msg = f"unsupported operand type(s) for -: {lhs_type!r} and {type(rhs)!r}"
        raise TypeError(msg)    else:        return subtract(lhs, rhs)复制代码

2. 右側では __rsub__() を使用します

しかし、 a が __sub__() を実装していない場合はどうなるでしょうか? a と b が異なる型の場合、b の __rsub__() を呼び出そうとします (__rsub__ の「r」は「right」を意味し、演算子の右側を意味します)。

演算の両側が異なる型である場合、これにより、両方が式を有効にしようとする機会が確実に得られます。それらが同じである場合、__sub__() がそれを処理すると仮定します。ただし、両方の実装が同一であっても、オブジェクトの一方が他方の (サブ) クラスである場合には、やはり __rsub__() を呼び出す必要があります。

3. 型は気にしないでください

これで、式の両側が操作に参加できるようになりました。しかし、何らかの理由でオブジェクトの型が減算をサポートしていない場合はどうなるでしょうか (例: 4 - "stuff" はサポートされていません)。この場合、__sub__ または __rsub__ ができることは NotImplemented を返すことだけです。

これは、Python が次の操作に進み、コードを正常に実行できるようにすることを示す Python に返される信号です。私たちのコードの場合、これは、メソッドが機能すると仮定する前に、メソッドの戻り値をチェックする必要があることを意味します。

# 减法的实现,其中表达式的左侧和右侧均可参与运算_MISSING = object()def sub(lhs: Any, rhs: Any, /) -> Any:
        # lhs.__sub__
        lhs_type = type(lhs)        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")        except AttributeError:
            lhs_method = _MISSING        # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")        except AttributeError:
            lhs_rmethod = _MISSING        # rhs.__rsub__
        rhs_type = type(rhs)        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs        if lhs_type is not rhs_type:
            calls = call_lhs, call_rhs        else:
            calls = (call_lhs,)        for first_obj, meth, second_obj in calls:            if meth is _MISSING:                continue
            value = meth(first_obj, second_obj)            if value is not NotImplemented:                return value        else:            raise TypeError(                f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
            )复制代码

4. サブクラスは親クラスよりも優先されます

__rsub__() のドキュメントを見ると、コメントがあることに気づきます。減算式の右側が左側のサブクラス (同じクラスではなく真のサブクラス) であり、2 つのオブジェクトの __rsub__() メソッドが異なる場合、 __sub__() が前に呼び出されます。最初に __rsub__() を呼び出します。つまり、b が a のサブクラスの場合、呼び出しの順序は逆になります。

これは奇妙な例外のように思えるかもしれませんが、その背後には理由があります。サブクラスを作成すると、親クラスが提供する操作に加えて新しいロジックを挿入することになります。この種のロジックを親クラスに追加する必要はありません。追加しないと、サブクラスでの操作時にサブクラスが実装したい操作を親クラスが簡単にオーバーライドしてしまいます。

具体的には、Spam という名前のクラスがあるとします。Spam() - Spam() を実行すると、LessSpam のインスタンスが取得されます。次に、Bacon という名前の Spam のサブクラスを作成します。これにより、Spam から Bacon を減算すると、VeggieSpam が得られます。

上記のルールがないと、Spam() - Bacon() は LessSpam になります。これは、Spam は、Bacon を減算すると VeggieSpam が得られることを知らないためです。

但是,有了上述规则,就会得到预期的结果 VeggieSpam,因为 Bacon.__rsub__() 首先会在表达式中被调用(如果计算的是 Bacon() - Spam(),那么也会得到正确的结果,因为首先会调用 Bacon.__sub__(),因此,规则里才会说两个类的不同的方法需有区别,而不仅仅是一个由 issubclass() 判断出的子类。)

# Python中减法的完整实现_MISSING = object()def sub(lhs: Any, rhs: Any, /) -> Any:
        # lhs.__sub__
        lhs_type = type(lhs)        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")        except AttributeError:
            lhs_method = _MISSING        # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")        except AttributeError:
            lhs_rmethod = _MISSING        # rhs.__rsub__
        rhs_type = type(rhs)        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs        if (
            rhs_type is not _MISSING  # Do we care?
            and rhs_type is not lhs_type  # Could RHS be a subclass?
            and issubclass(rhs_type, lhs_type)  # RHS is a subclass!
            and lhs_rmethod is not rhs_method  # Is __r*__ actually different?
        ):
            calls = call_rhs, call_lhs        elif lhs_type is not rhs_type:
            calls = call_lhs, call_rhs        else:
            calls = (call_lhs,)        for first_obj, meth, second_obj in calls:            if meth is _MISSING:                continue
            value = meth(first_obj, second_obj)            if value is not NotImplemented:                return value        else:            raise TypeError(                f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
            )复制代码

推广到其它二元运算

解决掉了减法运算,那么其它二元运算又如何呢?好吧,事实证明它们的操作相同,只是碰巧使用了不同的特殊/魔术方法名称。

所以,如果我们可以推广这种方法,那么我们就可以实现 13 种操作的语义:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。

由于闭包和 Python 在对象自省上的灵活性,我们可以提炼出 operator 函数的创建。

# 一个创建闭包的函数,实现了二元运算的逻辑_MISSING = object()def _create_binary_op(name: str, operator: str) -> Any:
    """Create a binary operation function.

    The `name` parameter specifies the name of the special method used for the
    binary operation (e.g. `sub` for `__sub__`). The `operator` name is the
    token representing the binary operation (e.g. `-` for subtraction).

    """

    lhs_method_name = f"__{name}__"

    def binary_op(lhs: Any, rhs: Any, /) -> Any:
        """A closure implementing a binary operation in Python."""
        rhs_method_name = f"__r{name}__"

        # lhs.__*__
        lhs_type = type(lhs)        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name)        except AttributeError:
            lhs_method = _MISSING        # lhs.__r*__ (for knowing if rhs.__r*__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name)        except AttributeError:
            lhs_rmethod = _MISSING        # rhs.__r*__
        rhs_type = type(rhs)        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name)        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs        if (
            rhs_type is not _MISSING  # Do we care?
            and rhs_type is not lhs_type  # Could RHS be a subclass?
            and issubclass(rhs_type, lhs_type)  # RHS is a subclass!
            and lhs_rmethod is not rhs_method  # Is __r*__ actually different?
        ):
            calls = call_rhs, call_lhs        elif lhs_type is not rhs_type:
            calls = call_lhs, call_rhs        else:
            calls = (call_lhs,)        for first_obj, meth, second_obj in calls:            if meth is _MISSING:                continue
            value = meth(first_obj, second_obj)            if value is not NotImplemented:                return value        else:
            exc = TypeError(                f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}"
            )
            exc._binary_op = operator            raise exc复制代码

有了这段代码,你可以将减法运算定义为 _create_binary_op(“sub”, “-”),然后根据需要重复定义出其它运算。

想了解更多编程学习,敬请关注php培训栏目!

以上がPythonの二項算術演算を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.imで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。