Jan-03-2019, 11:43 AM
Why do we need to overload operators?
overload operators
|
Jan-03-2019, 11:43 AM
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
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
Jan-04-2019, 12:23 PM
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
@
def __gt__(self,other): if self.size>other.size: return True return Falsecan 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 |
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
how operators are implemented as function calls | Skaperen | 5 | 4,521 |
Dec-15-2018, 03:14 AM Last Post: ichabod801 |