python在进行运算符重载时是否强制类型?

2024-06-16 12:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

a = str('5')
b = int(5)
a == b
# False

但如果我创建int的子类,并重新实现__cmp__

^{pr2}$

为什么这两个不同?python运行时是否捕捉到int.__cmp__()抛出的TypeError,并将其解释为False值?有人能给我指一下2.x cpython源代码中显示这是如何工作的位吗?在


Tags: 代码false源代码cpython子类intcmpstr
3条回答

a == b的比较决策树如下所示:

  • python调用a.__cmp__(b)
    • a检查{}是否是适当的类型
    • 如果b是适当的类型,则返回-10,或{}
    • 如果b不是,则返回NotImplented
  • 如果返回-10+1,则python完成;否则
  • 如果NotImplemented返回,请尝试
  • b.__cmp__(a)
    • b检查{}是否是适当的类型
    • 如果a是适当的类型,则返回-10,或{}
    • 如果a不是,则返回NotImplemented
  • 如果返回-10+1,则python完成;否则
  • 如果notimpletted再次返回,则答案是False

不是一个确切的答案,但希望能有所帮助。在

如果我对你的问题理解正确,你需要这样的东西:

>>> class A(int):
...     def __cmp__(self, other):
...         return super(A, self).__cmp__(A(other)) # < - A(other) instead of other
... 
>>> a = str('5')
>>> b = A(5)
>>> a == b
True

更新

关于2.x cpython源代码,您可以在函数wrap_cmpfunc中找到这个结果的原因,该函数实际上检查了两件事情:给定的比较函数是func,而{}是{}的子类型。在

^{pr2}$

文档在这一点上并不完全明确,但请参见here

If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a __cmp__ method or rich comparison methods like __gt__, described in section Special method names.

这(特别是“不同类型的对象”和“非内置类型的对象”之间的隐式对比)表明,对于内置类型,实际调用比较方法的正常过程被跳过:如果您试图比较两个不同(和非数字)内置类型的对象,它只会短路到自动False。在

相关问题 更多 >