0
Can someone tell implications of magic methods from python course. [ANSWERED] (MORE ANSWERS R Appreciated)
(_lt__ ,__le__ ,__eq__ ,__ne__ ,__gt__ ,__ge__) seems kind of overkill...isn't it better to define using normal functions???? THanks in advance
4 Antworten
+ 1
Say you have two objects, two sandwiches. You can add different things on each sandwich, but you cant compare them to eachother. If each sandwich item had a value and one the sandwich was made, each sandwich had a total value. Now you have a way to compare them! you could override the __gt__, __lt__ and whatever else to make it so, if one sandwich has a greater value, they are the "greater" sandwich.
s1 = Sandwich(sandwich_stuffs)
s2 = Sandwich(other_sand_stuffs)
print(s1 > s2)
# depends on whats in it but...
#output
True
A real stupid example, but i hope you can see the potential of operator overloading and how it helps interact with other objects.
+ 1
less than, less than or equal, equal to, not equal,........
you can change how your object reacts to those builtins.
less than == __lt__ == <
+ 1
Thanks a lot Slick it's a great example for a newbie like me but I might need a bit more practice for using it to it's full potential..
Thanks for u r assit🤓
0
Slick Thanks... can u pls tell how using overridden operators can be useful in coding