python:富比较运算符中的递归循环

Xof*_*off 5 python operators python-3.x

我不明白我的bug中的逻辑在哪里,所以我设法找到了一个最小的例子.我定义了一个类t,并说当你使用<=运算符并且a> = b必须计算b <= a时会发生一些事情.它工作正常

然后我得到的一个子类ut.当我比较两个值时,如果它们t都来自u它或两者都按预期工作,但如果一个来自类u而另一个来自类,t则它会失败.为什么

class t :
    def __le__(self,other) : return True
    def __ge__(self,other) : return(other<=self)
class u(t) :
    pass

a=t()
b=u()
#works
a<=a
a>=a
b<=b
b>=b
#works
a>=b
b<=a
#doesn't work RuntimeError: maximum recursion depth exceeded
a<=b
b>=a
Run Code Online (Sandbox Code Playgroud)

编辑:python 2.x(来自tobias_k)没有问题,但我想至少使用python 3.3

Val*_*ntz 6

当你这样做a <= b并且b是一个类的子类的实例时a,Python将首先调用b.__ge__('a')(然后在此调用返回时尝试其他方法NotImplemented)

以下是如何在没有无限递归的情况下实现它:

>>> class t:
...     def __le__(self, other):
...         return True
...     def __ge__(self, other):
...         return NotImplemented
... 
>>> class u(t):
...     pass
...
Run Code Online (Sandbox Code Playgroud)