OOP with MyTime
Akira Li
4kir4.1i at gmail.com
Wed Jul 2 15:45:28 EDT 2014
kjakupak at gmail.com writes:
> I'm trying to write a boolean function that takes two Mytime objects, t1 and t2 as arguments, and returns True if the object falls inbetween the two times.
>
> This is a question from the How to Think Like a Computer Scientist book, and I need help.
>
> What I've gotten so far:
>
> class MyTime:
> def __init__(self, hrs=0, mins=0, secs=0):
> self.hours = hrs
> self.minutes = mins
> self.seconds = secs
> def between(t1, t2):
> if float(t1 <= t3) and float(t3 < t2):
> return True
> else:
> return False
>
> I just don't understand how to make a function that uses MyTime objects into the boolean function? Any help would be great.
A method accepts the object itself as the first parameter:
import functools
@functools.total_ordering
class MyTime:
...
def inbetween(self, t1, t2):
"""Return whether `self` is in [t1, t2) right-open range."""
return t1 <= self < t2 # `self` is the object itself
def _astuple(self):
return (self.hours, self.minutes, self.seconds)
def __lt__(self, other):
"""Return whether `self < other`."""
return self._astuple() < other._astuple()
def __eq__(self, other):
"""Return whether `self == other`."""
return self._astuple() == other._astuple()
See
https://docs.python.org/3/library/functools.html#functools.total_ordering
Example:
>>> MyTime(1).inbetween(MyTime(0), MyTime(2))
True
It is equivalent to:
>>> MyTime(0) <= MyTime(1) < MyTime(2)
True
--
Akira
More information about the Python-list
mailing list