How can I evaluate +5 in Python?

How is work + 5 evaluated (spoiler alert: result is 5)?

Does + by calling the __add__ method? 5 will be " other " in:

 >>> other = 5 >>> x = 1 >>> x.__add__(other) 6 

So what is a “void” that allows you to add 5?

void.__add__(5)

Another hint:

 / 5 

gives an error message:

 TypeError: 'int' object is not callable 
+6
source share
3 answers

+ 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 
+7
source

Looks like you found one of three unary operators :

  • The unary plus operation +x calls the __ pos __ () method.
  • The unary negation operation -x calls the __ neg __ () method.
  • The operation unary not (or invert) ~x calls the __ invert __ () method.
+7
source

According to the reference to numeric literals :

Note that numeric literals do not contain a character; a phrase like -1 is actually an expression consisting of a unary operator - and literally 1 .

And the section for unary operators :

The unary operator - (minus) gives a negation of its numeric argument.

The unary operator + (plus) gives its numeric argument unchanged.

There is no unary operator / (divide), therefore an error.

Related "magic methods" ( __pos__ , __neg__ ) are described in the data model documentation .

+6
source

Source: https://habr.com/ru/post/987814/


All Articles