加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python 3.1中使用Duck键入排序的最小方法

发布时间:2020-12-16 22:13:06 所属栏目:Python 来源:网络整理
导读:在the manual说: in general, __lt__() and __eq__() are sufficient,if you want the conventional meanings of the comparison operators 但我看到了错误: assert 2 当我运行此测试时: from unittest import TestCaseclass IntVar(object): def __init_

在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

将首先尝试调用类型(a).__ lt __(a,b),如果这返回NotImplemented,它将调用类型(b).__ gt __(b,a).

文档中的引用是关于使比较适用于单一类型,并且上面的解释说明了为什么这对于单个类型就足够了.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读