Python引用传值总结

Python函数的参数传值使用的是引用传值,也就是说传的是参数的内存地址值,因此在函数中改变参数的值,函数外也会改变。

这里需要注意的是如果传的参数类型是不可改变的,如String类型、元组类型,函数内如需改变参数的值,则相当于重新新建了一个对象。

# 添加了一个string类型的元素添加到末尾

def ChangeList(lis):
    lis.append('hello i am the addone')
    print lis
    return

lis = [1, 2, 3]
ChangeList(lis)
print lis

得到的结果是:

[1,2,3, 'hello i am the addone']

[1,2, 3,'hello i am the addone']

def ChangeString(string):
    string = 'i changed as this'
    print string
    return

string = 'hello world'
ChangeString(string)
print string

String是不可改变的类型,得到的结果是:

i changed as this

hello world

  

  

原文地址:https://www.cnblogs.com/6tian/p/5802328.html