Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 2.__add__(3) work in Python?

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?

like image 315
Hanfei Sun Avatar asked Nov 15 '12 01:11

Hanfei Sun


People also ask

How does __ add __ work in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.

Can you have two methods with the same name in Python?

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.

What is __ INT __ in Python?

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.

What is __ sub __ in Python?

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.


1 Answers

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
like image 143
unutbu Avatar answered Sep 28 '22 09:09

unutbu