怎么可能在 Python 中计算 +5?

How is it possible to evaluate +5 in Python?

如何评估 + 5(剧透警告:结果为 5)?

+ 不是通过调用某些东西的 __add__ 方法来工作吗? 5 将是“other”在:

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

那么允许加5的"void"是什么?

void.__add__(5)

另一个线索是:

/ 5

抛出错误:

TypeError: 'int' object is not callable

根据 language reference on numeric literals:

Note that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator - and the literal 1.

section on unary operators:

The unary - (minus) operator yields the negation of its numeric argument.

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

没有一元 /(除法)运算符,因此出现错误。

相关的"magic methods"(__pos__,__neg__)在the data model documentation.

本例中的+调用了一元魔法方法__pos__ rather than __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只支持其中的4个(一元算术运算)__neg____pos____abs____invert__,因此SyntaxError/。请注意,__abs__ 与称为 abs() 的内置函数一起使用,即此一元运算没有运算符。


请注意 /5/ 后跟一些东西)仅在 IPython shell 中有不同的解释,对于正常的 shell 是语法错误正如预期的那样:

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's features.
%quickref -> Quick reference.
help      -> Python's 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

看起来你找到了三个之一 unary operators:

  • 一元加运算+x调用__pos__()方法。
  • 一元否定运算-x调用__neg__()方法。
  • 一元非(或反转)操作 ~x 调用 __invert__() 方法。