Doing some exercises from Think like a CS with Python 3: Have a task: Overload the necessary operator(s) that instead of having to write
if t1.after(t2):...
we can use the more convenient
if t1 > t2: ...
How I can do it? Have no ideas.
Doing some exercises from Think like a CS with Python 3: Have a task: Overload the necessary operator(s) that instead of having to write
if t1.after(t2):...
we can use the more convenient
if t1 > t2: ...
How I can do it? Have no ideas.
You need to override the t1.__gt__(t2)
method of your class. I would suggest overriding all of the following __gt__
__lt__
__le__
__ge__
special functions.
For example
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __lt__(self,other):
self_mag = (self.x ** 2) + (self.y ** 2)
other_mag = (other.x ** 2) + (other.y ** 2)
return self_mag < other_mag
will allow you to write expressions like p1 < p2
but not p1 > p2
. But it can be done trivially.
edit: turns out that simply overriding the __eq__
and __lt__
on top of using functools.@total_ordering
gives the desired result.