相关疑难解决方法(0)

如何在Python中处理__eq__以及按什么顺序处理?

由于Python不提供其比较运算符的左/右版本,它如何决定调用哪个函数?

class A(object):
    def __eq__(self, other):
        print "A __eq__ called"
        return self.value == other
class B(object):
    def __eq__(self, other):
        print "B __eq__ called"
        return self.value == other

>>> a = A()
>>> a.value = 3
>>> b = B()
>>> b.value = 4
>>> a == b
"A __eq__ called"
"B __eq__ called"
False
Run Code Online (Sandbox Code Playgroud)

这似乎称为两种__eq__功能.只是寻找官方的决策树.

python comparison user-defined

76
推荐指数
3
解决办法
9万
查看次数

在Python中为什么/什么时候`x == y`调用`y .__ eq __(x)`?

Python文档清楚地说明了x==y调用x.__eq__(y).然而,似乎在许多情况下,情况正好相反.它记录了何时或为何发生这种情况,以及如何确定我的对象__cmp____eq__方法是否会被调用.

编辑:只是为了澄清,我知道这__eq__是在优先考虑__cmp__,但我不清楚为什么y.__eq__(x)被优先调用x.__eq__(y),当后者是文档状态将发生.

>>> class TestCmp(object):
...     def __cmp__(self, other):
...         print "__cmp__ got called"
...         return 0
... 
>>> class TestEq(object):
...     def __eq__(self, other):
...         print "__eq__ got called"
...         return True
... 
>>> tc = TestCmp()
>>> te = TestEq()
>>> 
>>> 1 == tc
__cmp__ got called
True
>>> tc == 1
__cmp__ got called
True
>>> 
>>> 1 == te …
Run Code Online (Sandbox Code Playgroud)

python comparison operator-overloading

37
推荐指数
2
解决办法
1万
查看次数