简体   繁体   中英

Comparing class instances in python

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

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

You need to perform the type check in __cmp__ then act accordingly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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