__eq__ 在超级对象上
__eq__ on super objects
以下代码在 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.
中不起作用
请注意,此问题与
不重复
这里发生的是 Derived
的超级 class 是 int
。在 Python 2 中,int
没有实现 __lt__
、__gt__
或 __eq__
等丰富的比较运算符,因为它使用 __cmp__
代替。但是,Python 3 中不支持 __cmp__
,因此 int
在 [=] 中实现了 __lt__
、__gt__
和 __eq__
等丰富的比较运算符27=] 3.所以,在Python2中的Derived
中,super.__eq__
不存在,因为Python中不存在Python2.
以下代码在 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.
中不起作用请注意,此问题与
这里发生的是 Derived
的超级 class 是 int
。在 Python 2 中,int
没有实现 __lt__
、__gt__
或 __eq__
等丰富的比较运算符,因为它使用 __cmp__
代替。但是,Python 3 中不支持 __cmp__
,因此 int
在 [=] 中实现了 __lt__
、__gt__
和 __eq__
等丰富的比较运算符27=] 3.所以,在Python2中的Derived
中,super.__eq__
不存在,因为Python中不存在Python2.