【发布时间】:2016-09-19 18:18:50
【问题描述】:
当我尝试重写魔术方法 __eq__ 并使用 super 访问在 object 中找到的基本方法时,出现错误。这不可能是一个错误,但它确实感觉像一个:
class A(object):
def __eq__(self, other):
return super(A, self).__eq__(other)
A() == 0
# raises AttributeError: 'super' object has no attribute '__eq__'
这是不直观的,因为 object.__eq__ 存在,但对于 class A(object): pass 它不存在。如果我没记错__eq__ 诉诸is 检查,那么这可能是这里的解决方法,但使用is 而不是super 对mixin 不友好。在我的情况下走那条路是可以的,但在其他情况下可能不是。
任何关于为什么__eq__ 以这种方式工作的建议或信息都会很棒。
【问题讨论】:
-
该错误在 2.7 中出现,但在 3.5 中未出现
-
不,
object不支持 instances 上的__eq__...尝试object().__eq__,它将引发AttributeError...而不是object.__eq__ is (probably) a classmethod for checking if types are identical (egobject.__eq__(object)`) -
@donkopotamus:这不会将您的对象与
other进行比较;它会将新创建的“空白”对象与other进行比较。 -
@BrenBarn 我的意思是
object().__eq__甚至不起作用,它会引发属性错误(已编辑以使其清晰)
标签: python python-2.7 super python-object