In Python, what is the difference between add and __add__ methods?
In Python, what is the difference between add and __add__ methods?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A method called
addis just that – a method with that name. It has no special meaning whatsoever to the language or the interpreter. The only other thing that could be said about it is that sets have a method with the same name. That’s it, nothing special about it.The method
__add__is called internally by the+operator, so it gets special attention in the language spec and by the interpreter and you override it to define addition for object of a class. You don’t call it directly (you can – they’re still normal methods, they only get called implicitly in some circumstances and have some extra restrictions – but there’s rarely if ever a reason – let alone a good reason). See the docs on “special” methods for details and a complete list of other “special” methods.