+ 2
Some help me understand this challenge code!
Can someone, balance me real quick on this challenge code - I cannot make sense of it. https://code.sololearn.com/cMCMM5o5U4zo/# If you are lazy to open link: class malicious(int): def __init__(self, value): self = value def __mul__(self, x): return self - x def __add__(self, x): return self//x a = malicious(5) print (a) # We know that a=5 and it is <class '__main__.malicious'> print ((a+2) + a * 2) # Answer: 5 # But already from above a = 5, so if we substitute a with 5 we get: print ((5 + 2) + 5 * 2) # Answer: 17 # How is this possible???
2 Answers
+ 2
In your code, what seems to be happening is the class is using what is known as operator overloading to change how that class is handled when used alongside math. The __add__ overloader will make it so that whenever the class is added to something else, it will run whatever is within the curly brackets. In this case, instead of adding the class with another number, it will find the floor division of the two. The __mul__ operator is used to change how the class is handled under multiplication, in this case replacing it with subtraction.
When actually solving the problem, it can be viewed as this:
(5//2) + (5-2)
+ 2
had to reread that twice inorder to understand, thanks