2017-05-29 78 views
-1

我聲明瞭一個整數變量x,其值爲0python:'int'object has no attribute'__iadd__'

>>> x = 0 

當我運行這行:

>>> x += 3 
>>> x 
3 

一切順利。但是,當我跑這條線:

>>> x.__iadd__(3) 

Python引發一個異常:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'int' object has no attribute '__iadd__' 

爲什麼而official python documentationoperator模塊,與所述+=運營商調用__iadd__方法蟒蛇引發此異常?

+3

因爲如果沒有定義__iadd__,'x + = y'會回退到'x = x + y'。請參閱https://docs.python.org/3/reference/datamodel.html#object.__iadd__ – jonrsharpe

回答

5
operator模塊Python官方文檔

+=運營商調用__iadd__方法?

不,它說,a += b相當於a = operator.iadd(a, b),不a.__iadd__(b)

operator.iadd(a, b)不等於a.__iadd__(b)operator.iadd回落到__add____radd__如果__iadd__不存在或返回NotImplemented

3

它不這麼說;你要鏈接到的文檔中是operator模塊:

operator.iadd(a, b)
operator.__iadd__(a, b)

a = iadd(a, b)相當於a += b

operator模塊包含與運算符等相似的函數,它沒有定義標準的Python運算符。它沒有說任何關於x.__iadd__


相關的文檔,而this

object.__iadd__(self, other)

這些方法稱爲實現增強的算術作業(+=,...)。這些方法應嘗試就地操作(修改self)並返回結果(可能是,但不一定是,self)。 如果未定義特定的方法,則增強的分配將回到常規方法。 ...

所以,一個目的可以限定__iadd__來覆蓋+=操作的行爲,但是,如果沒有定義這樣的方法,它落在回默認a = a + b行爲。

相關問題