__cmp__ between dissimilar objects

insyte at gmail.com insyte at gmail.com
Mon Nov 13 19:33:17 EST 2006


I have a class that has, as an attribute, an instance of
datetime.datetime().  I would like to be able to compare my class
directly to instances of datetime.datetime in addition to other
instances of my class.  The value used for the comparison in either
case should be the value of the datetime attribute of the class:

from datetime import datetime

class GeneralizedTime(object):
    def __init__(self, time=None):
        if time is None:
            self.datetime = datetime.now()
    def __cmp__(self, x):
        if isinstance(x, GeneralizedTime):
            return cmp(self.datetime, x.datetime)
        if isinstance(x, datetime):
            return cmp(self.datetime, x)


>>> import datetime
>>>
>>> GeneralizedTime() > datetime.now()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare datetime.datetime to GeneralizedTime

Clearly I'm misunderstanding something, here.  As I understand my code,
I'm directly comparing an instance of datetime (self.datetime) to
another instance of datetime.

What am I failing to grasp?

Thanks!

-Ben




More information about the Python-list mailing list