If x is list, why does x += “ha” work, while x = x + “ha” throws an exception?

前端 未结 3 911
暖寄归人
暖寄归人 2021-01-31 14:35

From what little I know, + op for lists only requires the 2nd operand to be iterable, which \"ha\" clearly is.

In code:

>>> x = []
>>>          


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 15:16

    When defining operators, there are two different "add" operators: One is called __add__, the other __iadd__. The latter one is for in-place additions with +=, the other one is the regular + operator. http://docs.python.org/reference/datamodel.html has more infos on that.

提交回复
热议问题