如何在Python中评估+5?

Pas*_*ten 7 python operators addition

如何评估+ 5工作(扰流警报:结果是5)?

是不是+通过调用__add__方法来工作?5将在" other"中:

>>> other = 5
>>> x = 1
>>> x.__add__(other)
6
Run Code Online (Sandbox Code Playgroud)

那么允许添加5的"空白"是什么?

void.__add__(5)

另一个线索是:

/ 5
Run Code Online (Sandbox Code Playgroud)

抛出错误:

TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 8

在+这种情况下调用一元魔术方法__pos__,而不是__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
Run Code Online (Sandbox Code Playgroud)

蟒仅支持其中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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)


Ray*_*ger 7

看起来你已经找到了三个一元运算符中的一个:

  • 一元加运算+x调用__pos __()方法.
  • 一元否定操作-x调用__neg __()方法.
  • 一元not(或反转)操作~x调用__invert __()方法.


jon*_*rpe 6

根据数字文字的语言参考:

请注意,数字文字不包含符号; 类似的短语-1 实际上是由一元运算符-和文字组成的表达式1.

关于一元运算符的部分:

一元-(减号)运算符产生其数字参数的否定.

一元+(加号)运算符使其数字参数保持不变.

没有一元/(除)运算符,因此错误.

相关的"魔术方法"(__pos__,__neg__)包含在数据模型文档中.

  • 注意`/`实际上是一个`SyntaxError`,它是使用`/`做一些时髦的IPython shell. (2认同)