0

I've made a class for time. Now I want to define a function which shows whether one time is greater than the other or not. I've written my code to this level:

class Time:

    def __init__(self,Hour_value=0,Minute_value=0,Secound_value=0):
        self.Hour = Hour_value
        self.Minute = Minute_value
        self.Secound = Secound_value

    def __repr__(self):  
        return str(self.Hour)  + ":" + str(self.Minute) + ":" + str(self.Secound)

What should I do for the rest? Is There a built-in function for this task?

Moty.R
  • 47
  • 1
  • 9
  • 2
    To be able to use `>`, you need to implement [`__gt__`](https://docs.python.org/3/reference/datamodel.html#object.__gt__) on your `Time` class. – jkr Aug 04 '20 at 16:12
  • You need to write actual [comparison methods](https://docs.python.org/3/reference/datamodel.html#object.__lt__) if you want e.g. `>` to work. – jonrsharpe Aug 04 '20 at 16:12

1 Answers1

2

You should use the __lt__ method:

class Time:
    def __init__(self, Hour_value=0, Minute_value=0, Secound_value=0):
        self.Hour = Hour_value
        self.Minute = Minute_value
        self.Secound = Secound_value
    def __lt__(self, other):
        return (self.Hour, self.Minute, self.Secound) < (other.Hour, other.Minute, other.Secound)

Now you can do something like this:

times = [Time(3,4,5), Time(5,2,3), Time(3,4,7)]
sorted(times)

In general, you can compare two Time objects:

if Time(1,2,3) < Time(0,4,5):
    ...

__lt__ stands for "lower than". You can also implement __le__ ("lower or equal"), __eq__ ("equal"), __ne__ ("not equal"), __gt__ ("greater than") and __ge__ ("greater or equal").

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50