Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,当在一个新类中重写_eq__;()时,奇怪的事情发生了_Python - Fatal编程技术网

Python,当在一个新类中重写_eq__;()时,奇怪的事情发生了

Python,当在一个新类中重写_eq__;()时,奇怪的事情发生了,python,Python,我想在新的a类中覆盖eq,代码如下: >>> class A(object): ... def __eq__(self, obj): ... return True ... >>> a = A() >>> b = A() >>> L = [0, 0, a, 1] >>> L.index(a) 0 >>> L.index(0) 0 >>

我想在新的a类中覆盖eq,代码如下:

>>> class A(object):
...     def __eq__(self, obj):
...         return True
...     

>>> a = A()

>>> b = A()

>>> L = [0, 0, a, 1]

>>> L.index(a)
0

>>> L.index(0)
0

>>> L.index(100)
2

>>> L.index(1)
2

很难理解这是怎么发生的。

让我们从逻辑上假设
index()
在列表
L
中按顺序工作,从最低索引到最高索引,当它第一次遇到元素的
True
比较时停止

>>> L.index(a)
a==0
是第一个
True
匹配项,因此匹配
L
的第一个元素

>>> L.index(0)
>>> L.index(100)
>>> L.index(1)
0==0
是第一个
True
匹配项,因此匹配
L
的第一个元素

>>> L.index(0)
>>> L.index(100)
>>> L.index(1)
100==a
是第一个
True
匹配项,因此匹配
L
的第三个元素

>>> L.index(0)
>>> L.index(100)
>>> L.index(1)

1==a
是第一个
True
匹配项,因此匹配
L

的第三个元素,您不了解哪个部分/结果?当与
a
进行比较时,您总是会得到正确答案。为什么L.index(1)和L.index(100)返回2?很酷,我理解。Thx
\uuuu eq\uuuuuu
从本质上讲必须双向工作。也许这让你感到困惑(
a==100
也意味着
100==a
)。@Evert这是不正确的。查看其中的
x==y
但是
y!=x
。相等比较(使用
==
)调用左侧对象的
方法。如果失败(在本例中,
int
\uuuu eq\uuuu
不能用于比较
A
类型的对象),它将调用并尝试调用右侧对象的
\uu eq\uuu
。@MarkusMeskanen;我没有意识到,尽管
other
参数是一个赠品。
>>> L.index(0)
>>> L.index(100)
>>> L.index(1)