0
Can someone plz explain how this code works?
Apparently __init__ is a class constructor, and a class can have only one constructor. Then what are __mul__ and __add__. When do they get executed? What are the values of 'value' and 'x'. 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+2) + a*2)
1 Respuesta
+ 1
__init__ is called when new object is created and there can be more constructors (overloading)
value in init method is parameter that is passed when new object is created in your case malicious(5) so 5 is the value in your example.
__mul__ and __add__ are operator overloading methods
when you use object of class that has __mul__ method defined you can use * operator
mul is for multiplication, so its called when u call a*b when, variable a anb b are instances of class with __mul__ mehod defined
its same for __add__ but for + sign (adding)
when you have expression a * 5 method __mul__ is called as __mul__(a,5) so self is "a" and value is 5