Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3.1中Duck类型的最小排序方法_Python_Python 3.x_Duck Typing - Fatal编程技术网

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

Python3.1中Duck类型的最小排序方法,python,python-3.x,duck-typing,Python,Python 3.x,Duck Typing,他说: 一般来说,如果您想要 比较运算符的常规含义 但我看到了错误: > assert 2 < three E TypeError: unorderable types: int() < IntVar() >断言2

他说:

一般来说,如果您想要 比较运算符的常规含义

但我看到了错误:

>       assert 2 < three
E       TypeError: unorderable types: int() < IntVar()
>断言2<3
E类型错误:无序类型:int()
当我运行此测试时:

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
从unittest导入TestCase
类IntVar(对象):
def u u init u u;(self,value=None):
如果值不是None:value=int(值)
自我价值=价值
定义内部(自我):
回归自我价值
定义(自身、其他):
返回self.value
我很惊讶当
IntVar()
位于右侧时,
\uuuu int\uuuu()
没有被调用。我做错了什么

添加
\uuu gt\uuuu()
修复了这一问题,但这意味着我不明白订购的最低要求是什么

谢谢,
Andrew

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

a < b
a
将首先尝试调用
类型(a)。\uu lt\uuu(a,b)
,如果返回
NotImplemented
,它将调用
类型(b)。\ugt\uuu(b,a)

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


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

如果您查看它特别提到此行为--
这些方法没有交换参数版本(当左参数不支持该操作,但右参数支持该操作时使用);相反,_ult_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu是他们自己的反映。丰富的比较方法的参数从来都不是强制的。
@agf:Answers应该在Answers中,而不是在comments中。@EthanFurman文档不会像Sven的答案那样引导您了解具体案例,我认为这是值得作为答案而不仅仅是评论发布的必要条件。谢谢。我已经完全忘记了total_排序。这将非常好。total_排序在您的情况下有效。但是,两个不同的类都使用total_排序,可能会出现错误: