オペレーター関連のマジックメソッド

演算子に関連する魔法のメソッドは多すぎます。J は大まかに次の 2 つのカテゴリをリストします:

1. 比較演算子

__cmp__(self, other)if このメソッド負の数を返し、自己 < その他を示します。 正の数を返し、自己 > その他を示します。 0 を返し、自己 == その他を示します。 __cmp__ を定義することは強くお勧めできません。代わりに、__lt__、__eq__、およびその他のメソッドを個別に定義して比較関数を実装することをお勧めします。 __cmp__ は Python3 では非推奨になりました。 __eq__(self, other)比較演算子の動作を定義します ==__ne__(self, other) )比較演算子の動作を定義します !=__lt__(self, other) 比較演算子の動作を定義します <__gt__(self, other)比較演算子の動作を定義します>__le__(self, other) 比較演算子の動作を定義します <= __ge__(self, other) 比較演算子の動作を定義します >=

簡単な例を見ると理解できます:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Number(object):
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
        print('__eq__')
        return self.value == other.value
    def __ne__(self, other):
        print('__ne__')
        return self.value != other.value
    def __lt__(self, other):
        print('__lt__')
        return self.value < other.value
    def __gt__(self, other):
        print('__gt__')
        return self.value > other.value
    def __le__(self, other):
        print('__le__')
        return self.value <= other.value
    def __ge__(self, other):
        print('__ge__')
        return self.value >= other.value
if __name__ == '__main__':
    num1 = Number(2)
    num2 = Number(3)
    print('num1 == num2 ? --------> {} \n'.format(num1 == num2))
    print('num1 != num2 ? --------> {} \n'.format(num1 == num2))
    print('num1 < num2 ? --------> {} \n'.format(num1 < num2))
    print('num1 > num2 ? --------> {} \n'.format(num1 > num2))
    print('num1 <= num2 ? --------> {} \n'.format(num1 <= num2))
    print('num1 >= num2 ? --------> {} \n'.format(num1 >= num2))

出力結果は次のとおりです:

__eq__
num1 == num2 ? --------> False
__eq__
num1 != num2 ? --------> False
__lt__
num1 < num2 ? --------> True
__gt__
num1 > num2 ? --------> False
__le__
num1 <= num2 ? --------> True
__ge__
num1 >= num2 ? --------> False

2. 算術演算子

##マジックメソッド説明
##__and__(self, other) ビット演算の実装&__or__( self, other) ビット演算の実装`__xor__(self, other) ビット演算の実装^
魔法の方法手順
__add__(self, other) 加算演算を実装します
__sub__(self, other) 減算演算を実装します
__mul__(self, other) 乗算演算を実装します
__floordiv__( self, other) は // 演算子を実装します
___div__(self, other) は / 演算子を実装します このメソッドは Python3 で使用できます (非推奨)。その理由は、Python3 では、除算のデフォルトは true Division です。
__truediv__(self, other) は true Division を実装します。__future__ から宣言した場合のみ、このメソッドをインポートします。有効になります
#mod__(self, other) % 演算子と剰余演算を実装します
__divmod__(self, other) other) divmod() 組み込み関数を実装します
__pow__(self, other) ** 演算を実装します。N 乗演算
__lshift__(self, other) ビット演算を実装します<<
__rshift__(self, other) ビット演算の実装>>


学び続ける
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!