“超级"对象没有属性“__eq__" [英] 'super' object has no attribute '__eq__'

查看:59
本文介绍了“超级"对象没有属性“__eq__"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试覆盖魔术方法 __eq__ 并使用 super 访问在 object 中找到的基本方法时,出现错误.这不可能是一个错误,但它确实感觉像是一个错误:

When I try to override the magic method __eq__, and use super to access the base method found in object, I get an error. 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__'

这是不直观的,因为 object.__eq__ 存在,但对于 class A(object): pass 它不存在.如果我没记错的话 __eq__ 会使用 is 检查,所以这可能是这里的解决方法,但是使用 is 而不是 super 不是 mixin 友好的.就我而言,走那条路没问题,但在其他情况下可能不行.

This is unintuitive because object.__eq__ exists, but for class A(object): pass it doesn't. 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. Going that route is ok in my case, but in others it might not be.

任何关于 __eq__ 为何以这种方式工作的建议或信息都会很棒.

Any suggestions, or info on why __eq__ works this way would be great.

推荐答案

如 Will 的回答中所述,object() 实际上根本没有实现 __eq__ 实例(在python 2.7中).

As noted in Will's answer, object() does not actually implement __eq__ at all for instances (in python 2.7).

您被 object.__eq__ 存在的事实所欺骗,认为它必须是一种检查对象的实例是否相等的方法

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__实际上是一个类方法,继承自type,用于检查类型是否相等.

Instead, object.__eq__ is actually a class method, inherited from type, that is used to check if types are equal.

即处理object == intobject == object等表达式.

这篇关于“超级"对象没有属性“__eq__"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆