zoukankan      html  css  js  c++  java
  • Python函数的列表类型参数传递,list+=list与list=list+list的区别

    在python中,对于可变(mutable)类型的变量,有一个地方需要注意,那就是+=运算符

    太长不看版:python中,list+=list只会改变list,list=list+list会产生一个新的list

    以下是详细解释,也可以查看原文:

    The general answer is that += tries to call the __iadd__ special method, and if that isn't available it tries to use __add__ instead. So the issue is with the difference between these special methods.

    The __iadd__ special method is for an in-place addition, that is it mutates the object that it acts on. The __add__ special method returns a new object and is also used for the standard + operator.

    So when the += operator is used on an object which has an __iadd__ defined the object is modified in place. Otherwise it will instead try to use the plain __add__ and return a new object.

    That is why for mutable types like lists += changes the object's value, whereas for immutable types like tuples, strings and integers a new object is returned instead (a += b becomes equivalent to a = a + b).

    For types that support both __iadd__ and __add__ you therefore have to be careful which one you use. a += b will call __iadd__ and mutate a, whereas a = a + b will create a new object and assign it to a. They are not the same operation!

    >>> a1 = a2 = [1, 2]
    >>> b1 = b2 = [1, 2]
    >>> a1 += [3]          # Uses __iadd__, modifies a1 in-place
    >>> b1 = b1 + [3]      # Uses __add__, creates new list, assigns it to b1
    >>> a2
    [1, 2, 3]              # a1 and a2 are still the same list
    >>> b2
    [1, 2]                 # whereas only b1 was changed

    For immutable types (where you don't have an __iadd__a += b and a = a + b are equivalent. This is what lets you use += on immutable types, which might seem a strange design decision until you consider that otherwise you couldn't use += on immutable types like numbers!

  • 相关阅读:
    15 反转链表
    八大排序算法总结(2)
    八大排序算法总结(1)
    22从上往下打印二叉树
    19顺时针打印矩阵
    20包含min函数的栈
    SpringMVC-Mybatis整合和注解开发
    优雅的代码之选择不同支付方式
    利用freemarker+SAX解析xml的方式对excel文件字段校验
    pl/sql编程语言
  • 原文地址:https://www.cnblogs.com/ch459742906/p/6937761.html
Copyright © 2011-2022 走看看