Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
overload operators
#1
Why do we need to overload operators?
Reply
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
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
Reply
#4
Please use python and output tags when posting code and results. Here are instructions on how to use them.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
@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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how operators are implemented as function calls Skaperen 5 3,480 Dec-15-2018, 03:14 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020