简体   繁体   English

比较python中的类实例

[英]Comparing class instances in python

I built a new class in python which defines time with 6 figures (such as 18:45:00) 我在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

I have also defined many methods to make it work as it should. 我还定义了许多方法使其能够正常工作。 the problem I have is with the cmp method: 我的问题是cmp方法:

def __cmp__(self,other):
    return cmp(self.to_seconds(),other.to_seconds())

It works fine when I try to compare times, if I'm sorting a list of times it also works fine. 当我尝试比较时间时,如果我对时间列表进行排序,它也可以正常工作。 But if I'm trying to sort a list of times and integers or strings it also work. 但是,如果我尝试对时间和整数或字符串列表进行排序,则它也可以工作。 How can I define it to compare only times and to raise and error if trying to compare time with something that isn't. 如果试图将时间与非时间进行比较,我如何定义它以仅比较时间并引发错误。

You can use isinstance() to see if the argument is an instance of some class. 您可以使用isinstance()来查看参数是否为某个类的实例。 See documentation . 请参阅文档

You need to perform the type check in __cmp__ then act accordingly. 您需要在__cmp__执行类型检查,然后采取相应措施。

For example, maybe something like this: 例如,也许是这样的:

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 is the constant to return for undefined comparison actions: http://docs.python.org/library/constants.html NotImplemented是用于返回未定义比较操作的常量: http : //docs.python.org/library/constants.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM