+ 2

What's the difference between this two code in python?

i) a.__add__(b) ii) int.__add__(a,b) As per my understanding in python everything is object so here in first code 'a' is an instance of a int class and __add__() method id defined inside this int class. Next, we passing 'b' as an argument to this instance method __add__() And, this whole this is equivalent to a + b But what does this second code is doing? I wonder does it call __add__() directly via class? If yes then how __add__() can take different argument. As here we passing two value and in first one we passing only one value. but __add__() can only be defined only one time inside int class? https://code.sololearn.com/ciFvufZ3K3Wy/?ref=app

13th Aug 2021, 8:24 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
4 Answers
+ 1
Tushar Kumar 🇼🇳 I suppose that the dot syntax is just a sugar coating over the classic function definition syntax. Whenever a method is called on an object with the dot syntax, the 'self' parameter is automatically given its value. However, calling it directly via the class leaves this self parameter untouched as there's nothing to assign the first parameter with, thus, requiring two arguments. That's what I think it is. Needs clarification though.
14th Aug 2021, 5:16 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Calvin Thomas Thanks! I tried something what you said practically and it work. I can finally say that self is just a syntactic sugar (which internally acutally passing a reference of an instance) but instead of it we can manually pass object. class AddTen: def add(self,x): print(x+10) one = AddTen() one.add(10) AddTen.add(one,10) https://code.sololearn.com/c976vcTVUKdE/?ref=app
14th Aug 2021, 7:20 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 1
Tushar Kumar 🇼🇳 That's a great conclusion, but always make sure that you verify your speculations. What's obvious might not necessarily be the truth.
14th Aug 2021, 7:39 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Calvin Thomas Well said brother..Thank you.
14th Aug 2021, 10:35 AM
I Am a Baked Potato
I Am a Baked Potato - avatar