python中 is、==、>、<究竟是如何比较的

is 比较的什么

先说结论:

is 比较两个对象的 id 值是否相等,是否指向同一个内存地址;

s1 = "nnm"
s2 = "nnm"
s1 is s2
id(s1), id(s2)
True
(2047633770800, 2047633770800)

这里虽然定义了两个变量,但是他们指向了同一字符串,也就是说内存地址是一样的。

我们在看下序列对象的比较。

l1 = [1, 2, 3]
l2 = l1.copy()
l1 == l2
l1 is l2
id(l1), id(l2)
True
False
(2047633789824, 2047624512512)

== 比较什么

class A:
    def __init__(self):
        self.value = 2

    def __eq__(self, o):
        the_value = self.value
        other_value = o.value
        return True if the_value == other_value else False


class B:
    def __init__(self, value):
        self.value = value
print(A() == B(2))
print(A() == B(3))
True
False

我们这里定义两个类,A和B, 而 A() == B(2) 的实质则是

A().__eq__(B(2))

A定义了一个__eq__方法,进行比较时则把对象B传入这个函数中,进行比较。

> < 比较什么

大小于比较则与==比较相似,这里用的方法则为__gt__ 和 __lt__

class A:
    def __init__(self):
        self.value = 2

    def __eq__(self, o):
        the_value = self.value
        other_value = o.value
        return True if the_value == other_value else False

    def __gt__(self, other):
        print("这里是比较大于")
        return False

    def __lt__(self, other):
        print("这里是比较小于")
        return True
print(A() < B(1))
print(A() > B(5))

为何要注意 is 和 == 的使用场景

我们知道如果is成立那么肯定成立,那么我们是不是可以直接使用判断不使用is呢?

我们略微修改一下

class A:
    def __eq__(self, o):
        print("执行比较")
        the_value = self.value
        other_value = o.value
        return True if the_value == other_value else False
A = A()
B = A
print(B == A)
print(id(B), id(A))
执行比较
True
1989813876096 1989813876096

我们可以看到变量A,B指向同一对象,但是在执行==的时候,并不会因为他们的id值是一样的而先判断id,而是走到了__eq__ 方法中。

而is要比== 要快的多,所以做判断时,这点应该去注意。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值