The integer 2
has an __add__
method:
>>> "__add__" in dir(2)
True
... but calling it raises a SyntaxError:
>>> 2.__add__(3)
File "<stdin>", line 1
2.__add__(3)
^
SyntaxError: invalid syntax
Why can't I use the __add__
method?
The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.
Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.
The __int__ method is called to implement the built-in int function. The __index__ method implements type conversion to an int when the object is used in a slice expression and the built-in hex , oct , and bin functions.
Python's object. __sub__(self, other) method returns a new object that represents the difference of two objects. It implements the subtraction operator - in Python.
2.
is parsed as a float, so 2.__add__
is a SyntaxError.
You can evaluate
(2).__add__(3)
instead.
In [254]: (2).__add__(3)
Out[254]: 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With