Python Forum

Full Version: overload operators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why do we need to overload operators?
Do you mean overloading functions by it's call signature?
Sometimes it's useful to have one function, which depends on input type.
https://docs.python.org/3/library/functo...ledispatch
I never used it in real applications.

Another cool feature are the magic methods. You control the behavior of an object.
But I guess this does not answer your question.
To compare two objects, we can overload operators in Python. We understand 3>2. But what is orange>apple? Let’s compare apples and oranges now.
>>> class fruit:
       def __init__(self,type,size):
               self.type='fruit'
               self.type=type
               self.size=size
       def __gt__(self,other):
               if self.size>other.size:
                        return True
               return False
>>> orange=fruit('orange',7)
>>> apple=fruit('apple',8)
>>> apple>orange
True

>>> orange>apple
False
Please use python and output tags when posting code and results. Here are instructions on how to use them.
@rinu, just note that

def __gt__(self,other):
    if self.size>other.size:
        return True
    return False
can be just

def __gt__(self, other):
    return self.size > other.size