【问题标题】:__eq__ on super objects__eq__ 在超级对象上
【发布时间】:2016-11-28 16:54:35
【问题描述】:

以下代码在 Python 3 (3.5.2) 中运行良好,但在 Python 2 (2.7.12) 中引发 AttributeError: 'super' object has no attribute '__eq__'

class Derived(int):

    def __eq__(self, other):
        return super(Derived, self).__eq__(other)


a, b = Derived(1024), Derived(1729)
print(a == b)

Python 3 行为是预期的。我试图理解为什么它在 Python 2 中不起作用。

请注意,这个问题不是'super' object has no attribute '__eq__'的重复问题

【问题讨论】:

  • 因为在 Python 2 中 int 没有丰富的比较运算符(参见 here)。 Python 3 实现了丰富的比较运算符,因为 __cmp__ 已被弃用。

标签: python python-2.7 super


【解决方案1】:

这里发生的是Derived 的超类是int。在 Python 2 中,int 没有实现丰富的比较运算符,例如 __lt____gt____eq__,因为它使用了 __cmp__。但是,__cmp__ 在 Python 3 中不受支持,因此int 在 Python 3 中实现了丰富的比较运算符,例如 __lt____gt____eq__。因此,在 Python 2 中的 Derived 中,super.__eq__不存在,因为int.__eq__ 在 Python 2 中不存在。

【讨论】:

  • 我有点假设 int 从这个 __eq__ 实现 >>> int.__eq__ <method-wrapper '__eq__' of type object at 0x000000001E298C40> 但现在我尝试了 int.__eq__(1, 2) 并得到了一个错误。 int.__eq__(0) 返回 NotImplemented 你能详细说明这一切是如何工作的吗?
  • 在 python 2 中,int.__eq__int 类与另一个类进行比较,而不是比较ints。所以int.__eq__(int) 为真,但int.__eq__(float) 为假。
  • 有道理。感谢您的澄清。
  • 不用担心。 Python 2 中有一些与此相关的奇怪特性。 Python 3 试图更好地标准化。
猜你喜欢
  • 2016-09-19
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多