使用"进行平等检查"操作者

时间:2017-11-24 03:47:17

标签: python list

使用以下语法时会发生什么?

>>> 1 == 1 in [1]
True
>>> 1 == 2 in [1]
False

使其更复杂:

>>> class A:
        def __init__(self):    
                self.i = 0
        def __call__(self):
                self.i += 1
                return self.i
>>> a = A()
>>> a()
1
>>> 2 == 2 in [a(), a()] # Here a() should only be evaluated once
True
>>> a() # But in fact it was evaluated twice
4
>>> 5 == 6 in [a(), a()] # Here a() should be evaluated twice because in need to compare with each elements in the list
False
>>> a() # But in fact it was not evaluated at all
5

我读到in运算符正在调用列表的__contains__方法,但是

>>> [1].__contains__(1 == 1) # 1 is equal to True
True
>>> [2].__contains__(2 == 2)
False

据我所知,以前没有问过这个问题。现在真的让我感到困惑,所以任何信息都会非常感激!

0 个答案:

没有答案