简体   繁体   English

内置和用户定义类型之间的Python比较

[英]Python comparison between built-in and user-defined types

How does Python 3 compare a built-in object (on the lhs) to a user-defined object (on the rhs)? Python 3如何将内置对象(在lhs上)与用户定义的对象(在rhs上)进行比较?

Does the built-in __eq__ method simply delegate the comparison to the rhs ( rhs.__eq__(self) )? 内置的__eq__方法是否只是将比较委托给rhs( rhs.__eq__(self) )?

I didn't find any statement about this in the docs. 我在文档中没有找到任何关于此的陈述。 The docs state: 文档说明:

Objects of different types, except different numeric types, never compare equal. 除了不同的数字类型之外,不同类型的对象永远不会相等。

It's quite misleading because: 这是误导,因为:

class X:
  def __eq__(self, rhs)
    return True

x = X()
'abc' == x # True

I think the doc statement should be rephrased as follows: 我认为文件陈述应该改写如下:

Objects of different built-in types, except different numeric types, never compare equal. 除了不同的数字类型之外,不同内置类型的对象永远不会相等。

and should furthermore clarify how the comparison to user-defined class instances is performed. 并且应该进一步说明如何执行与用户定义的类实例的比较。

To answer the questions: 回答问题:

How does Python 3 compare a built-in object (on the lhs) to a user-defined object (on the rhs)? Python 3如何将内置对象(在lhs上)与用户定义的对象(在rhs上)进行比较?

The same way as with any other object comparisons (including None !). 与任何其他对象比较(包括None !)的方式相同。

Does the built-in __eq__ method simply delegate the comparison to the rhs ( rhs.__eq__(self) )? 内置的__eq__方法是否只是将比较委托给rhs( rhs.__eq__(self) )?

No. The built-in __eq__ does not delegate like this. 号内置__eq__ 没有委托这个样子。 There is a higher-construct at work that covers the behavior of == in Python. 在工作中有一个更高的构造,它涵盖了Python中==的行为。

Given a == b , where a.__eq__(b) returns NotImplemented then b.__eq__(a) will be invoked and the result of the used as the result of the equality test. 给定a == b ,其中a.__eq__(b) 返回 NotImplemented则将调用b.__eq__(a) ,并将used的结果作为相等测试的结果。 ( False is returned if both __eq__ implementations return NotImplemented .) (如果两个__eq__实现都返回NotImplemented则返回False 。)

Thus, given x (of class X ), and given that "abc".__eq__(x) returns NotImplemented , then x.__eq__("abc") is invoked (and evaluates to True per the question). 因此,给定x (类X ),并且给定"abc".__eq__(x) 返回 NotImplemented ,则调用x.__eq__("abc") (并根据问题求值为True )。

The same applies to the other standard comparison operators. 这同样适用于其他标准比较运算符。

While I don't care to speculate too much on the documentation (or possible mis-wording), I believe it is entirely accurate if taken in context of stdObj.__eq__(obj) as opposed to stdObj == obj . 虽然我不想过多地推测文档(或可能的误写),但我认为如果stdObj.__eq__(obj)上下文中stdObj.__eq__(obj)而不是stdObj == obj ,则完全准确。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM