Python比较运算符重载

Python比较运算符重载,python,datetime,comparison,operator-overloading,Python,Datetime,Comparison,Operator Overloading,对于我的Python 2.7.3项目,我有一个名为custom\u date的类,它有一个名为fixed\u date的属性: from datetime import date class custom_date(): def __init__(self, fixed_date): self.fixed_date = fixed_date def __lt__(self, other): return self.fixed_date <

对于我的Python 2.7.3项目,我有一个名为
custom\u date
的类,它有一个名为
fixed\u date
的属性:

from datetime import date
class custom_date():
    def __init__(self, fixed_date):
        self.fixed_date = fixed_date

    def __lt__(self, other):
        return self.fixed_date < other

    #__gt__, __ge__, __le__, __eq__, __ne__ all implemented the same way

有什么办法可以解决这个问题吗?

我想我知道你为什么会遇到问题。查看docs.python.org上的

>>> y > x
电话:

y.__gt__(x)
x只是一个实例对象,而不是其中存储的fixed_date属性:

>>> x
<__main__.custom_date instance at 0x020D78C8>
>>> x.fixed_date
datetime.date(2012, 2, 1)

我认为要“修复”这一点,您必须将所有日期都设置为custom_date类型。其他人可能会为您提供更好的解决方案,我会关注,因为我也很好奇。

只需子类
date
即可获得此功能。由于datetime对象是不可变的,因此需要使用
\uuuuu new\uuuuu
构造函数vs
\uuuuuu init\uuuu

from datetime import date
class custom_date(date):
    def __new__(cls, year,month,day):
        return date.__new__(cls, year, month,day)

x = custom_date(2013,2,1)
y = date(2013,2,2)

print x<y
print y<x
由于用于比较的确定类是,因此左侧的类需要具有正确的比较运算符来处理与右侧的类的比较。如果这两个类都没有比较运算符,则实例将按标识(它们的内存地址)排序。您的错误本质上是试图将苹果与橙色进行比较:将标识与日期类进行比较


请注意,Python 2.1中曾经有一个rcmp来处理此类问题。和的引入也导致了
\uu\cmp\uu
被弃用

找到了一个潜在的解决方案,以防其他人也面临同样的问题

从:

换句话说,date1但是,如果另一个比较对象具有timetuple()属性,则返回NotImplemented。此钩子为其他类型的日期对象提供了实现混合类型比较的机会。如果没有,则在将日期对象与其他类型的对象进行比较时,将引发TypeError,除非比较为==或!=。后一种情况分别返回False或True

如果
x.\uuuuuuuuuuuuuuuuuuy)
返回
NotImplemented
而不是引发
TypeError
,Python将自动尝试反向比较
y.\uuuuuuuuuuuuux)
(有关比较的更多信息)

date
但是,如果另一个对象不是
date
对象,则会引发
TypeError
,除非另一个对象实现了timetuple()属性

因此,解决方案是向我的类添加一个伪
timetuple()
方法

from datetime import date
class custom_date():
    def __init__(self, fixed_date):
        self.fixed_date = fixed_date

    def __lt__(self, other):
        return self.fixed_date < other

    #__gt__, __ge__, __le__, __eq__, __ne__ all implemented the same way

    def timetuple():
        pass
from datetime导入日期
类自定义日期():
定义初始日期(自我,固定日期):
self.fixed\u date=固定日期
定义(自身、其他):
返回自固定日<其他
#__gt、ge、le、eq、ne都以相同的方式实现
def timetuple():
通过

谢谢您提供的信息。我希望有一种方法可以进行“反射式”比较,比如
\uuuuradd\uuuuuuu
\uuuuu add\uuuuuu
。似乎比较运算符是不可能的。我想你应该接受@dawg的答案,接受这个!答案很好,但OP自己的答案是“正确的”(而且更简单)解决方案,因为它不会强迫您不必要地将date子类化。
from datetime import date
class custom_date(date):
    def __new__(cls, year,month,day):
        return date.__new__(cls, year, month,day)

x = custom_date(2013,2,1)
y = date(2013,2,2)

print x<y
print y<x
True
False
from datetime import date
class custom_date():
    def __init__(self, fixed_date):
        self.fixed_date = fixed_date

    def __lt__(self, other):
        return self.fixed_date < other

    #__gt__, __ge__, __le__, __eq__, __ne__ all implemented the same way

    def timetuple():
        pass