+ in this case calls the unary magic method __pos__ , not __add__ :
>>> class A(int): def __pos__(self): print '__pos__ called' return self ... >>> a = A(5) >>> +a __pos__ called 5 >>> +++a __pos__ called __pos__ called __pos__ called 5
Python only supports 4 (unary arithmetic operations) of which __neg__ , __pos__ , __abs__ and __invert__ , so SyntaxError with / . Please note that __abs__ works with the built-in abs() function, i.e. there is no operator for this unary operation.
Note that /5 ( / followed by something) is interpreted differently only by the IPython shell, for a normal shell this is a syntax error, as expected:
Ashwinis-MacBook-Pro:py ashwini$ ipy Python 2.7.6 (default, Sep 9 2014, 15:04:36) Type "copyright", "credits" or "license" for more information. IPython 3.0.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython features. %quickref -> Quick reference. help -> Python own help system. object? -> Details about 'object', use 'object??' for extra details. >>> /5 Traceback (most recent call last): File "<ipython-input-1-2b14d13c234b>", line 1, in <module> 5() TypeError: 'int' object is not callable >>> /float 1 1.0 >>> /sum (1 2 3 4 5) 15
Ashwinis-MacBook-Pro:~ ashwini$ python Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> /5 File "<stdin>", line 1 /5 ^ SyntaxError: invalid syntax >>> /float 1 File "<stdin>", line 1 /float 1 ^ SyntaxError: invalid syntax
source share