• 六、运算符相关的魔术方法
    • 1、比较运算符
    • 2、算术运算符

    六、运算符相关的魔术方法

    运算符相关的魔术方法实在太多了,j就大概列举下面两类:

    1、比较运算符

    魔术方法 说明
    __cmp__(self, other) 如果该方法返回负数,说明 self < other; 返回正数,说明 self > other; 返回 0 说明 self == other。强烈不推荐来定义 __cmp__ , 取而代之, 最好分别定义 __lt__, __eq__ 等方法从而实现比较功能。 __cmp__ 在 Python3 中被废弃了。
    __eq__(self, other) 定义了比较操作符 == 的行为
    __ne__(self, other) 定义了比较操作符 != 的行为
    __lt__(self, other) 定义了比较操作符 < 的行为
    __gt__(self, other) 定义了比较操作符 > 的行为
    __le__(self, other) 定义了比较操作符 <= 的行为
    __ge__(self, other) 定义了比较操作符 >= 的行为

    来看个简单的例子就能理解了:

    1. #!/usr/bin/env python3
    2. # -*- coding: UTF-8 -*-
    3. class Number(object):
    4. def __init__(self, value):
    5. self.value = value
    6. def __eq__(self, other):
    7. print('__eq__')
    8. return self.value == other.value
    9. def __ne__(self, other):
    10. print('__ne__')
    11. return self.value != other.value
    12. def __lt__(self, other):
    13. print('__lt__')
    14. return self.value < other.value
    15. def __gt__(self, other):
    16. print('__gt__')
    17. return self.value > other.value
    18. def __le__(self, other):
    19. print('__le__')
    20. return self.value <= other.value
    21. def __ge__(self, other):
    22. print('__ge__')
    23. return self.value >= other.value
    24. if __name__ == '__main__':
    25. num1 = Number(2)
    26. num2 = Number(3)
    27. print('num1 == num2 ? --------> {} \n'.format(num1 == num2))
    28. print('num1 != num2 ? --------> {} \n'.format(num1 == num2))
    29. print('num1 < num2 ? --------> {} \n'.format(num1 < num2))
    30. print('num1 > num2 ? --------> {} \n'.format(num1 > num2))
    31. print('num1 <= num2 ? --------> {} \n'.format(num1 <= num2))
    32. print('num1 >= num2 ? --------> {} \n'.format(num1 >= num2))

    输出的结果为:

    1. __eq__
    2. num1 == num2 ? --------> False
    3. __eq__
    4. num1 != num2 ? --------> False
    5. __lt__
    6. num1 < num2 ? --------> True
    7. __gt__
    8. num1 > num2 ? --------> False
    9. __le__
    10. num1 <= num2 ? --------> True
    11. __ge__
    12. num1 >= num2 ? --------> False

    2、算术运算符

    魔术方法 说明
    __add__(self, other) 实现了加号运算
    __sub__(self, other) 实现了减号运算
    __mul__(self, other) 实现了乘法运算
    __floordiv__(self, other) 实现了 // 运算符
    ___div__(self, other) 实现了/运算符. 该方法在 Python3 中废弃. 原因是 Python3 中,division 默认就是 true division
    __truediv__(self, other) 实现了 true division. 只有你声明了 from __future__ import division 该方法才会生效
    __mod__(self, other) 实现了 % 运算符, 取余运算
    __divmod__(self, other) 实现了 divmod() 內建函数
    __pow__(self, other) 实现了 ** 操作. N 次方操作
    __lshift__(self, other) 实现了位操作 <<
    __rshift__(self, other) 实现了位操作 >>
    __and__(self, other) 实现了位操作 &
    __or__(self, other) 实现了位操作 ` `
    __xor__(self, other) 实现了位操作 ^

    最后,如果对本文感兴趣的,可以关注下公众号:

    公众号