python3.1中Duck类型排序的最小方法

2024-05-18 17:52:23 发布

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

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()

当我运行此测试时:

^{pr2}$

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

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

谢谢, 安德鲁


Tags: andtheinltyouifmanualare
1条回答
网友
1楼 · 发布于 2024-05-18 17:52:23

python3.x永远不会对运算符执行任何类型强制,因此在这个上下文中不使用__int__()。比较

a < b

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

文档中引用的内容是使比较适用于单一类型,上面的解释说明了为什么这对于单个类型来说就足够了。在

要使您的类型与int正确交互,您应该实现所有的比较运算符,或者使用python2.7或3.2中提供的^{} decorator。在

相关问题 更多 >

    热门问题