+ 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

1st Nov 2019, 5:55 PM
Chum4k3r
Chum4k3r - avatar
4 Respuestas
+ 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
1st Nov 2019, 6:49 PM
Russ
Russ - avatar
+ 3
Russ thank you, I learned something new :)
1st Nov 2019, 7:49 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Woooooowww this was surprisingly awesome! Thanks man
1st Nov 2019, 6:56 PM
Chum4k3r
Chum4k3r - avatar
+ 1
Ha, no worries.
1st Nov 2019, 7:00 PM
Russ
Russ - avatar