>>> 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
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.
a == b
的比较决策树如下所示:a.__cmp__(b)
a
检查{b
是适当的类型,则返回-1
,0
,或{b
不是,则返回NotImplented
-1
、0
或+1
,则python完成;否则b.__cmp__(a)
b
检查{a
是适当的类型,则返回-1
,0
,或{a
不是,则返回NotImplemented
-1
、0
或+1
,则python完成;否则False
不是一个确切的答案,但希望能有所帮助。在
如果我对你的问题理解正确,你需要这样的东西:
更新
关于2.x cpython源代码,您可以在函数}是{}的子类型。在
^{pr2}$wrap_cmpfunc
中找到这个结果的原因,该函数实际上检查了两件事情:给定的比较函数是func
,而{文档在这一点上并不完全明确,但请参见here:
这(特别是“不同类型的对象”和“非内置类型的对象”之间的隐式对比)表明,对于内置类型,实际调用比较方法的正常过程被跳过:如果您试图比较两个不同(和非数字)内置类型的对象,它只会短路到自动False。在
相关问题 更多 >
编程相关推荐