+ 5
What's the purpose of __radd__() in python? I don't understand how it work. Please explain with examole.
2 Respostas
+ 7
Take a look at following example,
class a:
def __init__(self,num):
self.num=num
def __add__(self,other):
print(self.num+other.num)
class b:
def __init__(self,num):
self.num=num
#def __radd__(self,other):
# print(self.num+other.num)
num1=a(5)
num2=b(6)
num1+num2
In the code above i create two objects and add them. Since num1 is the first object in expression "num1+num2" , the num1 add method is called first , so self refers to num1 and other object is the right to "+".
Now if you comment out the the add method in class a.Then you will get an error since num1 has no add method . You can do do num2+num1 if num2 has a add method but if you still want it to be num1+num2 , then python will look for __radd__ method in other object class(b) and if it finds one then it will do reverse addition(i.e. num2+num1).
Uncomment the radd method in class b to see it working
+ 4
Abhay Omg this one is the best explanation. I searched everywhere but no clear explanation. This one cleared my Concept. Thank you