int() 对象如何使用“=="?python2中没有__eq__()方法的运算符? [英] How int() object uses "==" operator without __eq__() method in python2?

查看:41
本文介绍了int() 对象如何使用“=="?python2中没有__eq__()方法的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我阅读了Fluent python"并了解了 == 运算符如何使用 __eq__() 方法与 python 对象一起工作.但是它如何与 python2 中的 int 实例一起工作?

<预><代码>>>>一 = 1>>>乙 = 1>>>a == b真的>>>a.__eq__(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>AttributeError: 'int' 对象没有属性 '__eq__'

在python3中所有a.__eq__(b)返回True

解决方案

Python 更喜欢使用丰富的比较函数(__eq____lt____ne__ 等),但如果没有存在,它回退到使用单个比较函数(__cmp__,在 Python 3 中删除):

<块引用>

这些是所谓的丰富比较"方法,优先于下面的 __cmp__() 调用比较运算符.

Python 2 整数类型没有实现丰富的比较功能:

PyTypeObject PyInt_Type = {...(cmpfunc)int_compare,/* tp_compare */...0,/* tp_richcompare */

在 Python 3 中,整数类型(现在很长)只实现了丰富的比较函数,因为 Python 3 放弃了对 __cmp__ 的支持:

PyTypeObject PyLong_Type = {...long_richcompare,/* tp_richcompare */

这就是 (123).__eq__ 不存在的原因.相反,Python 2 在测试两个整数的相等性时回退到 (123).__cmp__:

<预><代码>>>>(1).__eq__(2)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>AttributeError: 'int' 对象没有属性 '__eq__'>>>(1).__cmp__(2)-1

Recently I read the "Fluent python" and understood how == operator works with python objects, using __eq__() method. But how it works with int instances in python2?

>>> a = 1
>>> b = 1
>>> a == b
True
>>> a.__eq__(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__eq__'

in python3 all a.__eq__(b) returns True

解决方案

Python prefers to use rich comparison functions (__eq__, __lt__, __ne__, etc.), but if those don't exist, it falls back to using a single comparison function (__cmp__, removed in Python 3):

These are the so-called "rich comparison" methods, and are called for comparison operators in preference to __cmp__() below.

The Python 2 integer type doesn't implement a rich comparison function:

PyTypeObject PyInt_Type = {
    ...
    (cmpfunc)int_compare,                       /* tp_compare */
    ...
    0,                                          /* tp_richcompare */

In Python 3, the integer type (now a long) implements only a rich comparison function, since Python 3 dropped support for __cmp__:

PyTypeObject PyLong_Type = {
    ...
    long_richcompare,                           /* tp_richcompare */

This is why (123).__eq__ doesn't exist. Instead, Python 2 falls back to (123).__cmp__ when testing the equality of two integers:

>>> (1).__eq__(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__eq__'
>>> (1).__cmp__(2)
-1

这篇关于int() 对象如何使用“=="?python2中没有__eq__()方法的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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