【问题标题】:python : recursion loop in rich comparison operatorpython:富比较运算符中的递归循环
【发布时间】:2014-05-09 15:17:59
【问题描述】:

我不明白我的错误的逻辑在哪里,所以我设法找到了一个最小的例子。我定义了一个类t,并说当你使用=b 必须计算b

然后我从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

【问题讨论】:

  • a 和 b 是哪个类?
  • @akaRem 抱歉,我添加了a 和b 的定义。
  • 仅供参考,在 Python 2.x 中它按预期“工作”(始终返回 true)。
  • @tobias_k 谢谢,我编辑了我的问题以包含您的评论。
  • 问题似乎与比较器替换有关,因为对 return(other&lt;=self) 的调用似乎改为检查 self &gt;= other,导致无限递归......但是,我不知道 为什么 确实如此,为什么只在最后两种情况下...

标签: python python-3.x operators


【解决方案1】:

当你做a &lt;= 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
...

【讨论】:

猜你喜欢
  • 2018-05-27
  • 2018-11-11
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2016-07-18
相关资源
最近更新 更多