[英]'super' object has no attribute '__eq__'
When I try to override the magic method __eq__
, and use super
to access the base method found in object
, I get an error. 当我尝试覆盖魔术方法__eq__
,并使用super
访问object
找到的基本方法时,我收到一个错误。 There's no way this is a bug, but it sure feels like one: 这不是一个错误,但它确实感觉像一个:
class A(object):
def __eq__(self, other):
return super(A, self).__eq__(other)
A() == 0
# raises AttributeError: 'super' object has no attribute '__eq__'
This is unintuitive because object.__eq__
exists, but for class A(object): pass
it doesn't. 这是不直观的,因为object.__eq__
存在,但是对于class A(object): pass
它没有。 If I'm not mistaken __eq__
resorts to an is
check, so that may be the workaround here, but using is
instead of super
isn't mixin friendly. 如果我没有记错__eq__
度假村一个is
检查,这样可以在这里是解决办法,但使用is
不是super
不混入友好。 Going that route is ok in my case, but in others it might not be. 在我的情况下,这条路线是可以的,但在其他情况下可能不是。
Any suggestions, or info on why __eq__
works this way would be great. 有关__eq__
为何如此工作的任何建议或信息都会很棒。
As noted in Will's answer, object()
does not actually implement __eq__
at all for instances (in python 2.7). 正如Will的回答所述, object()
实际上并没有为实例实现__eq__
(在python 2.7中)。
You are being deceived by the fact that object.__eq__
exists into believing it must be a method that checks if instances of object are equal 你被object.__eq__
存在而被欺骗,因为它必须是一种检查对象实例是否相等的方法
Instead, object.__eq__
is actually a class method, inherited from type
, that is used to check if types are equal. 相反, object.__eq__
实际上是一个继承自type
的类方法,用于检查类型是否相等。
That is, to handle expressions such as object == int
and object == object
. 也就是说,要处理诸如object == int
和object == object
表达式。
This is because object()
doesn't actually implement an __eq__()
. 这是因为object()
实际上并没有实现__eq__()
。 The "default" here would be: 这里的“默认”是:
class A(object):
def __eq__(self, other):
if self is other:
return True
return self == other
But, if what you're attempting had worked, you would actually be checking whether the self
instance of the parent class equaled other
. 但是,如果您尝试的工作有效,您实际上将检查父类的self
实例是否等于other
实例。 And, it's the same object ( self
), so it would. 并且,它是相同的对象( self
),所以它会。 So the closest equivalent of your code would actually be: 所以最接近你的代码实际上是:
class A(object):
def __eq__(self, other):
if self is other:
return True
return super(A, self) == other
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.