When is “i += x” different from “i = i + x” in Python?

后端 未结 3 594
栀梦
栀梦 2020-11-22 01:20

I was told that += can have different effects than the standard notation of i = i +. Is there a case in which i += 1 would be differen

3条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:54

    Under the covers, i += 1 does something like this:

    try:
        i = i.__iadd__(1)
    except AttributeError:
        i = i.__add__(1)
    

    While i = i + 1 does something like this:

    i = i.__add__(1)
    

    This is a slight oversimplification, but you get the idea: Python gives types a way to handle += specially, by creating an __iadd__ method as well as an __add__.

    The intention is that mutable types, like list, will mutate themselves in __iadd__ (and then return self, unless you're doing something very tricky), while immutable types, like int, will just not implement it.

    For example:

    >>> l1 = []
    >>> l2 = l1
    >>> l1 += [3]
    >>> l2
    [3]
    

    Because l2 is the same object as l1, and you mutated l1, you also mutated l2.

    But:

    >>> l1 = []
    >>> l2 = l1
    >>> l1 = l1 + [3]
    >>> l2
    []
    

    Here, you didn't mutate l1; instead, you created a new list, l1 + [3], and rebound the name l1 to point at it, leaving l2 pointing at the original list.

    (In the += version, you were also rebinding l1, it's just that in that case you were rebinding it to the same list it was already bound to, so you can usually ignore that part.)

提交回复
热议问题