2015-05-24 73 views
6

評估+ 5如何工作(擾流警報:結果爲5)?如何在Python中評估+5?

是不是+通過調用__add__方法工作? 5將是 「other」 中:

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

那麼,什麼是 「無效」,允許添加5?

void.__add__(5)

另一條線索是:

/ 5 

引發錯誤:

TypeError: 'int' object is not callable 
+3

後者'TypeError'與IPython自動括號功能有關,它用'whatever()'替換'/ whatever'。 Python沒有一元'/'運算符。 – bereal

+0

@bereal任何連結到這個功能?它不僅僅是自動括號:'/ sum(1 2 3 4 5)'返回15. –

+0

@AshwiniChaudhary描述[here](https://ipython.org/ipython-doc/dev/interactive/reference.html #自動括號和引號),(與IPython的'?'-help相同)。顯然,它比所描述的要先進得多,例如'/'abc''返回''abc'',我不知道這意味着什麼。 – bereal

回答

7

在這種情況下+調用一元魔術方法__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 

的Python只支持4(一元的算術運算)__neg____pos____abs__,和__invert__,因此SyntaxError/。請注意,__abs__與一個稱爲abs()的內置函數一起工作,即沒有操作員進行這種一元操作。


注意/5/之後的東西)是不同的IPython的外殼僅解釋,對於正常的外殼不出所料語法錯誤:

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

不知道你爲什麼包含'__abs__'以及其他3 – wim

+0

@wim'__abs__'沒有一元運算符,但仍然被認爲是一元運算。 –

+0

我不認爲你是正確的 - [文檔定義](https://docs.python.org/2/reference/expressions.html#unary-arithmetic-and-bitwise-operations)顯然是一個' u_expr'並只提及減號,加號和反轉操作。你爲什麼要調用'int .__ abs__'這個一元操作,而不是'int .__ nonzero__'或其他? – wim

6

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.

沒有一元運算符/(除)運算符,因此錯誤。

相關「魔術方法」__pos____neg__)包含在the data model documentation

+0

我明白了...現在的解釋讓我評估' - +++ - 1',然後邏輯工作。 – PascalVKooten

+0

@PascalvKooten是的,你可以任意鏈接它們 – jonrsharpe

+2

請注意,'/'實際上是一個'SyntaxError',它是IPython shell用'/'做一些簡單的事情。 –

7

它看起來就像你找到的三個之一一樣unary operators

  • 一元加運算+x調用__pos __()方法。
  • 一元否定操作-x調用__neg __()方法。
  • 一元非(或反轉)操作~x調用__invert __()方法。