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要比== 要快的多,所以做判断时,这点应该去注意。