python中a += b 和a = a + b



  • a += b

    a1 = range(3)
    a2 = a1
    a2 += [3]
    a1
    # [output] [0, 1, 2, 3]
    a2
    # [output] [0, 1, 2, 3]
    

    a = a + b

    a1 = range(3)
    a2 = a1
    a2 = a1 + [3]
    a1
    # [output] [0, 1, 2]
    a2
    # [output] [0, 1, 2, 3]
    

    两种的区别只出现在可变对象中,对应可变对象(如list)。a+=b其实是调用了__iadd__方法,返回None,且在原对象上修改。a=a+b则是调用了__add__方法,会产生一个新的对象,所以不会改变a1的值。

    但是在不可变对象中(如int),就没有区别,因为根本就没有__iadd__方法,直接会调用__add__方法。


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

Looks like your connection to Dian was lost, please wait while we try to reconnect.