I have a class that has, as an attribute, an instance of
datetime.dateti me(). I would like to be able to compare my class
directly to instances of datetime.dateti me 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.dateti me, x.datetime)
if isinstance(x, datetime):
return cmp(self.dateti me, x)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime
Clearly I'm misunderstandin g 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
datetime.dateti me(). I would like to be able to compare my class
directly to instances of datetime.dateti me 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.dateti me, x.datetime)
if isinstance(x, datetime):
return cmp(self.dateti me, x)
>>import datetime
>>>
>>GeneralizedTi me() datetime.now()
>>>
>>GeneralizedTi me() datetime.now()
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime
Clearly I'm misunderstandin g 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
Comment