[英]Minimum Methods for Ordering with Duck Typing in Python 3.1
在手册中说:
通常,如果您想要比较运算符的常规含义,__
__lt__()
和__eq__()
就足够了
但我看到错误:
> 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
正确交互,您应该实现所有比较运算符,或者使用 Python 2.7 或 3.2 中提供的total_ordering
装饰器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.