2014-03-30 95 views
5

我不明白我的bug中的逻辑在哪里,所以我设法找到一个最小的例子。我定义了一个类t,并说当您使用< =运算符时发生了某些情况,并且a> = b必须计算b < = a。 它工作正常python:丰富的比较运算符递归循环

然后,我从t派生子类u。 当我比较两个值时,如果它们都来自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 

编辑:在Python 2.x的(从tobias_k)没有问题,但我想使用Python 3.3至少

+0

哪一类是a和b? – akaRem

+0

@akaRem对不起,我添加了'a'和'b'的定义。 – Xoff

+1

只是在FYI中,在Python 2.x中它“按预期工作”(始终返回true)。 –

回答

6

当你做a <= bba一个子类的实例的类,Python会首先调用b.__ge__('a')(再尝试其他的方法,如果这个调用返回NotImplemented

这里是如何实现它没有无限递归:

>>> class t: 
...  def __le__(self, other): 
...   return True 
...  def __ge__(self, other): 
...   return NotImplemented 
... 
>>> class u(t): 
...  pass 
... 
+1

它是一个记录的功能? – Xoff

+0

我敢肯定,我在文档中看到过,但我找不到在哪里 –

+0

请参阅http://stackoverflow.com/questions/13799386/python-bug-with-le-ge以获取类似的问题和答案。该文档似乎是http://docs.python.org/3/reference/datamodel.html#emulating-numeric-types(用于覆盖子类和使用NotImplemented作为@ValentinLorentz建议)的组合,以及http:// docs .python.org/3/reference/datamodel.html#“__le __”和“__ge __”的#basic-customization是彼此的反映。看起来好像一个人必须从这两部分中将自己的说明合在一起。 –