我正在研究一个库,它实现了一个数据结构,可以处理任何有序的数据类型——范围集。当你允许正无穷大和负无穷大时,很多操作(比如反转)变得有趣起来。
一个目标是让DATEIME对象与这个模块一起工作,并且在用非数字对象支持无穷大时,我已经创建了无穷大和负无穷大:class _Indeterminate(object):
def __eq__(self, other):
return other is self
@functools.total_ordering
class _Infinity(_Indeterminate):
def __lt__(self, other):
return False
def __gt__(self, other):
return True
def __str__(self):
return 'inf'
__repr__ = __str__
@functools.total_ordering
class _NegativeInfinity(_Indeterminate):
def __lt__(self, other):
return True
def __gt__(self, other):
return False
def __str__(self):
return '-inf'
INFINITY = _Infinity()
NEGATIVE_INFINITY = _NegativeInfinity()
不幸的是,当在CMP-()操作的左侧时,这对DATETIME对象不起作用:
In [1]: from rangeset import *
In [2]: from datetime import datetime
In [3]: now = datetime.now()
In [4]: cmp(INFINITY, now)
Out[4]: 1
In [5]: cmp(now, INFINITY)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/axiak/Documents/rangeset/ in ()
----> 1 cmp(now, INFINITY)
TypeError: can't compare datetime.datetime to _Infinity
我希望我能通过使用一个CMP包装器来绕过这个限制,它只是确保了我的对象总是被调用,但是我真的想使用.sort()方法,它会在这些对象之间调用CMP。
有没有办法创造一个比任何其他物体都小,比任何其他物体都大的物体?
模块主页:https://github.com/axiak/py-rangeset
最佳答案:
从docs
为了防止比较回到
比较对象地址时,日期比较通常会引发类型错误
如果另一个比较项不是日期对象。然而,
如果另一个比较对象具有
timetuple()属性。
因此,为了允许与datetime对象进行比较,添加一个timetuple方法,例如class _Infinity(object):
def __lt__(self, other):
return False
def __gt__(self, other):
return True
def timetuple(self):
return tuple()
import datetime
INF = _Infinity()
now = datetime.datetime.now()
print cmp(INF, now)
print cmp(now, INF)
输出:
1
-1