-3

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.

Alex
  • 29
  • 4
  • 1
    Look at [this link](https://www.geeksforgeeks.org/dunder-magic-methods-python/), and the [documentation](https://docs.python.org/3/reference/datamodel.html?highlight=__gt__#object.__gt__). – rassar Mar 28 '20 at 20:29
  • What have you tried so far, where exactly do you struggle with this task? – Grzegorz Skibinski Mar 28 '20 at 20:29
  • 1
    Show us what you tried so far. You can use the `__gt__` operator. – Laurent LAPORTE Mar 28 '20 at 20:30
  • 1
    @rassar thx got it) – Alex Mar 28 '20 at 20:36
  • You should really search stack overflow for your question before you post it. There are many answers about operator overloading already. Here's one questions with several: https://stackoverflow.com/questions/1552260/rules-of-thumb-for-when-to-use-operator-overloading-in-python – livingtech Apr 10 '20 at 15:29

1 Answers1

2

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.

Alex Petrosyan
  • 473
  • 2
  • 20