+ 3
Magic methos and operands order
I've implemented a magic method to add integers values to values stored in some list-based container object. >>> obj+1 operation works as expected, but I've been wondering if the opposite >>> 1+obj Would work, and it doesn't. I know this way it calls the int().__add___() method. Is there a way to make it work like the first case? Example code: https://code.sololearn.com/cJVe46U2K4Jo/?ref=app
4 Réponses
+ 6
Add the __radd__() magic method to define its behaviour. radd is reverse add, so when __add__() defines behaviour for con + 1, __radd__() defines behaviour for 1 + con.
Demo: https://code.sololearn.com/ctapB7EXYBZG/?ref=app
+ 3
Russ thank you, I learned something new :)
+ 2
Woooooowww this was surprisingly awesome! Thanks man
+ 1
Ha, no worries.