English 中文(简体)
是否有办法比较某一类别中的变量
原标题:Is there a way to compare variables in a class
  • 时间:2023-09-24 14:31:49
  •  标签:
  • python

I m在比较一类变量方面存在问题

当我打电话<条码>(t2.between(t1, t3)

这是我发现的错误:

Traceback (most recent call last):
  File "e:CS-OOP-Fall 2023Classtest1.py", line 18, in <module>
    print(t2.between(t1, t3)) # is t2 between t1 and t3 as a method
          ^^^^^^^^^^^^^^^^^^
  File "e:CS-OOP-Fall 2023MyTime.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)

我对两件事进行了审判,但没有一件事奏效,我对变数的其他部分进行了审判,但似乎没有做正确的工作。

最后,我想说的是<代码>True或False,其依据是你选择检查的时间,但我想看一下其他工作是否首先奏效。

问题回答

<代码>MyClass的数值如何? 其特性之一是在评价<条码>时使用何种特性?

You have to use the magic method __lt__ to indicate python how to make a comparison:

from datetime import datetime

class MyTime:
    def __lt__(self, other):
        my_time = datetime.strptime("%H:%M:%S", f"{self.hours}:{self.minutes}:{self.seconds}")
        other_time = datetime.strptime("%H:%M:%S", f"{other.hours}:{other.minutes}:{other.seconds}")
        return my_time < other_time




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签