小能豆

有没有办法比较类中的变量

python

我在比较我创建的类中的变量时遇到问题

当我打电话时print(t2.between(t1, t3))

这是我得到的错误:

Traceback (most recent call last):
  File "e:\CS-OOP-Fall 2023\Classtest1.py", line 18, in <module>
    print(t2.between(t1, t3)) # is t2 between t1 and t3 as a method
          ^^^^^^^^^^^^^^^^^^
  File "e:\CS-OOP-Fall 2023\MyTime.py", line 81, in between
    return (t1 < self < t3)
            ^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'MyTime' and 'MyTime'

这是课程:

class MyTime:

    def __init__(self, hrs=0, mins=0, secs=0):

        """ Create a new MyTime object initialized to hrs, mins, secs.
           The values of mins and secs may be outside the range 0-59,
           but the resulting MyTime object will be normalized.
        """

       # Calculate total seconds to represent
        totalsecs = hrs*3600 + mins*60 + secs
        self.hours = totalsecs // 3600        # Split in h, m, s
        leftoversecs = totalsecs % 3600
        self.minutes = leftoversecs // 60
        self.seconds = leftoversecs % 60

    def __str__(self):
        # 0 - hours, 1 - minutes, 2 - seconds
        return ("{0}:{1}:{2}".format(self.hours, self.minutes, self.seconds))  

    def add_time(self, t2):

        h = self.hours + t2.hours
        m = self.minutes + t2.minutes
        s = self.seconds + t2.seconds

        while s >= 60:
            s -= 60
            m += 1

        while m >= 60:
            m -= 60
            h += 1

        sum_t = MyTime(h, m, s)
        return sum_t 

    def increment(self, seconds):
        self.seconds += seconds

        while self.seconds >= 60:
            self.seconds -= 60
            self.minutes += 1

        while self.minutes >= 60:
            self.minutes -= 60
            self.hours += 1  

    def to_seconds(self):
        """ Return the number of seconds represented
            by this instance
        """
        return self.hours * 3600 + self.minutes * 60 + self.seconds

    def after(self, t2, t3):
        """ Return True if I am strictly greater than both t2 and t3
        """
        if self.hours > t2.hours and self.hours > t3.hours:
            return True
        if self.hours < t2.hours or self.hours < t3.hours:
            return False

        if self.minutes > t2.minutes and self.minutes > t3.minutes:
            return True
        if self.minutes < t2.minutes or self.minutes < t3.minutes:
            return False

        if self.seconds > t2.seconds and self.seconds > t3.seconds:
            return True
        if self.seconds < t2.seconds or self.seconds < t3.seconds:
            return False

        return False


    def between(self, t1, t3):
        """Checks if one of the specified times falls between
           another the other times with True or False as a indicator
        """
        # this will cover both cases
        return (t1 < self < t3)

我尝试了一些方法,但没有一个起作用,我尝试了变量的其他部分,但它似乎不起作用

最后,我想让它说TrueFalse基于你选择检查的时间,但我想先看看其他东西是否有效。


阅读 109

收藏
2023-09-25

共1个答案

小能豆

根据你提供的代码和错误信息,问题出现在你的 between 方法中,具体来说是在这一行:

return (t1 < self < t3)

错误消息提示说不能在两个 MyTime 对象之间使用 < 运算符。要解决这个问题,你可以在 MyTime 类中定义一个特殊方法 __lt__(less than的缩写),该方法用于定义 < 运算符的行为。这样,你就可以在 between 方法中使用 < 运算符来比较两个 MyTime 对象。

在你的 MyTime 类中添加以下方法:

def __lt__(self, other):
    """Define the behavior of the '<' operator for MyTime objects."""
    if self.hours < other.hours:
        return True
    elif self.hours == other.hours and self.minutes < other.minutes:
        return True
    elif self.hours == other.hours and self.minutes == other.minutes and self.seconds < other.seconds:
        return True
    return False

这个方法将根据小时、分钟和秒逐一比较两个 MyTime 对象,并返回适当的布尔值。

然后,你的 between 方法应该能够正常工作:

def between(self, t1, t3):
    """Checks if one of the specified times falls between
       another the other times with True or False as an indicator
    """
    return (t1 < self < t3)

现在,你可以调用 print(t2.between(t1, t3)),它应该能够返回 TrueFalse,根据 t2 是否在 t1t3 之间。

2023-09-25