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