python - 在 Python 3.1 中使用 Duck Typing 进行排序的最少方法

标签 python python-3.x duck-typing

the manual是说:

in general, __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators

但我看到错误:

>       assert 2 < three
E       TypeError: unorderable types: int() < IntVar()

当我运行这个测试时:

from unittest import TestCase

class IntVar(object):

    def __init__(self, value=None):
        if value is not None: value = int(value)
        self.value = value

    def __int__(self):
        return self.value

    def __lt__(self, other):
        return self.value < other

    def __eq__(self, other):
        return self.value == other

    def __hash__(self):
        return hash(self.value)

class DynamicTest(TestCase):

    def test_lt(self):
        three = IntVar(3)
        assert three < 4
        assert 2 < three
        assert 3 == three

令我惊讶的是,当 IntVar() 在右边时,__int__() 没有被调用。我做错了什么?

添加 __gt__() 修复了这个问题,但这意味着我不明白订购的最低要求是什么......

谢谢, 安德鲁

最佳答案

Python 3.x 永远不会对运算符进行任何类型强制转换,因此在此上下文中不使用 __int__()。对比

a < b

将首先尝试调用type(a).__lt__(a, b),如果返回NotImplemented,它将调用type(b) .__gt__(b, a).

文档中的引述是关于对单一类型进行比较,上面的解释说明了为什么这对单一类型就足够了。

要使您的类型与 int 正确交互,您应该实现所有比较运算符,或使用 total_ordering decorator在 Python 2.7 或 3.2 中可用。

关于python - 在 Python 3.1 中使用 Duck Typing 进行排序的最少方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10054937/

相关文章:

python - 如何将一个类中所有对象共享的变量增加 1?

pattern-matching - "Iterating"通过异步方法

c# - 现有对象实例上的鸭子类型(duck typing)/动态代理

python - 如何将 QLabel 转换为 QTableWidgetItem 以放入 QTableWidget

与命令行 curl 相比,python facebook sdk 对 facebook 的调用速度很慢

python - SimpleConnectionPool 与 ThreadedConnectionPool : what it means to be thread safe?

python - 根据列表中的每个第 n 个元素对字典进行排序

python - 从 Python 中的直方图中获取数据点

python - TypeError: 'function' 对象不可下标 python。我正在尝试将每个 .mp4 文件合并为一个视频

ruby-on-rails - 我可以用鸭子类型(duck typing)改进这种方法吗?