我聲明瞭一個整數變量x
,其值爲0
。python:'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 documentation爲operator
模塊,與所述+=
運營商調用__iadd__
方法蟒蛇引發此異常?
因爲如果沒有定義__iadd__,'x + = y'會回退到'x = x + y'。請參閱https://docs.python.org/3/reference/datamodel.html#object.__iadd__ – jonrsharpe