__radd__ Function in Python
Hi everyone, In this post, we are going to learn about the __radd __ function in Python language.
But, before going through this post you must have prior knowledge of class and objects in Python.
You should also have the information about the operator overloading.
If you don’t have that then you will not able to get this post.
Now I will take an example to make you understand what is this __radd__ function and why it is used.
Okay, let’s begin:-
Let us have a class name sample which is consists of a function add which takes an argument and concate that argument with the data available in the class.
Please make sure that the class which we make must be the parameterized constructor.
Now come to the main function which has three objects named s1,s2,s3.
Pass the arguments in these objects.
Now recall the __add__ function by using the + Operator this + will access this add function directly.
Now take a look at the code
class sample: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other.a Ob1=sample("Code-") Ob2=sample("Speedy") Ob3=Ob1 +Ob2 print(Ob3)
If we use Ob3=Ob2+Ob1 then it will show an error because we are returning self. a + other.a but we are passing other.a+self.a.
So to overcome this we use the __radd__ function it will add this also and return other.a + self.a.
So take a look at the __radd__ function with Python code:-
class sample: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other.a def __radd__(self, other): return other.a + self.a Ob1=sample("Code-") Ob2=sample("Speedy") Ob3=Ob2 +Ob1 print(Ob3) # By Shrimad
Here is the output:-