__cmp__ between dissimilar objects

Fredrik Lundh fredrik at pythonware.com
Tue Nov 14 07:33:11 EST 2006


insyte at gmail.com wrote:

>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.

sure looks like you're comparing a datetime instance against a GeneralizeTime
instance to me.

why not just inherit from datetime instead?  or read footnote 4 under "supported
operations" on this page for info on how to implement mixed-type comparisions:

    http://docs.python.org/lib/datetime-datetime.html

</F> 






More information about the Python-list mailing list