gpt4 book ai didi

python - 在python中为任何对象创建无穷大和负无穷大

转载 作者:太空狗 更新时间:2023-10-30 02:49:23 25 4
gpt4 key购买 nike

我正在开发一个库,该库实现了一种适用于任何有序数据类型的数据结构——范围集。当您允许正无穷大和负无穷大时,许多操作(如反转)会变得有趣。

一个目标是让日期时间对象与这个模块一起工作,为了支持非数字对象的无穷大,我创建了 INFINITY 和 NEGATIVE_INFINITY:

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() 操作左侧的日期时间对象不起作用:

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/<ipython-input-5-c928d3687d92> in <module>()
----> 1 cmp(now, INFINITY)

TypeError: can't compare datetime.datetime to _Infinity

我曾希望我可以通过使用 cmp 包装器来绕过这个限制,它只确保我的对象总是被调用,但我真的想使用 .sort() 方法,这将导致 cmp在这些对象之间调用。

有没有办法创建一个真正小于任何其他对象,真正大于任何其他对象的对象?

模块主页:https://github.com/axiak/py-rangeset

最佳答案

来自 docs

In order to stop comparison from falling back to the default scheme of comparing object addresses, date comparison normally raises TypeError if the other comparand isn’t also a date object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute.

因此为了允许与日期时间对象进行比较,添加一个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

关于python - 在python中为任何对象创建无穷大和负无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com