[英]Comparing class instances in python
我在python中建立了一个新类,该类定义了6位数字的时间(例如18:45:00)
class Time(object):
def __init__(self, hour, minute, second):
minute = minute + second / 60
hour = hour + minute / 60
self.hour = hour % 24
self.minute = minute % 60
self.second = second % 60
我还定义了许多方法使其能够正常工作。 我的问题是cmp方法:
def __cmp__(self,other):
return cmp(self.to_seconds(),other.to_seconds())
当我尝试比较时间时,如果我对时间列表进行排序,它也可以正常工作。 但是,如果我尝试对时间和整数或字符串列表进行排序,则它也可以工作。 如果试图将时间与非时间进行比较,我如何定义它以仅比较时间并引发错误。
您可以使用isinstance()
来查看参数是否为某个类的实例。 请参阅文档 。
您需要在__cmp__
执行类型检查,然后采取相应措施。
例如,也许是这样的:
import numbers
def __cmp__(self, other):
other_seconds = None
if hasattr(other, "to_seconds"):
other_seconds = other.to_seconds()
elif isinstance(other, numbers.Real):
other_seconds = other
if seconds is None:
return NotImplemented
return cmp(self.to_seconds(), seconds)
def __cmp__(self, other):
if not isinstance(other, Time):
return NotImplemented
return cmp(self.to_seconds(), other.to_seconds())
NotImplemented
是用于返回未定义比较操作的常量: http : //docs.python.org/library/constants.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.