超详细Python教程——运算符相关的魔术方法

运算符相关的魔术方法实在太多了,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)定义了比较操作符 >= 的行为

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

#!/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、算术运算符

魔术方法说明
__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)实现了位操作 ^

  • 33
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月流霜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值