日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python函数参数传递机制_Python 学习笔记(一) 理解Python的函数传参机制

發布時間:2025/3/8 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python函数参数传递机制_Python 学习笔记(一) 理解Python的函数传参机制 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對于剛接觸Python不久的新手,Python的函數傳參機制往往會讓人迷惑。學過C的同學都知道函數參數可以傳值或者傳地址。比如下面這段代碼

點擊(此處)折疊或打開

void func(int input) {

input = 100;

}

int a = 0;

func(a);

printf("%d", a);

結果應該是打印0,a的值自始至終都沒有改變,因為傳遞給函數func的是a變量的一個拷貝。而下面這段代碼,

點擊(此處)折疊或打開

void func(int* input) {

*input = 100;

}

int a = 0;

func(&a);

printf("%d", a);

則會打印100,因為傳遞給func的參數是變量a的地址。

那么Python遇到類似情況是怎么樣處理的呢?以下摘自Mark Lutz的Learning Python第五版,

Python’s pass-by-assignment scheme isn’t quite the same as C++’s reference parameters

option, but it turns out to be very similar to the argument-passing model of the C

language (and others) in practice:

Immutable arguments are effectively passed “by value.”Objects such as integers

and strings are passed by object reference instead of by copying, but because

you can’t change immutable objects in place anyhow, the effect is much like making

a copy.

Mutable arguments are effectively passed “by pointer.”Objects such as lists

and dictionaries are also passed by object reference, which is similar to the way C

passes arrays as pointers—mutable objects can be changed in place in the function,

much like C arrays.

Of course, if you’ve never used C, Python’s argument-passing mode will seem simpler

still—it involves just the assignment of objects to names, and it works the same whether

the objects are mutable or not.

也就是說在Python中,不可變參數(Immutable arguments)都是可理解為傳值的,而可變參數(Mutable arguments)都是可以理解為傳地址的。而哪些類型是不可變參數呢,根據Mark的描述,numbers,strings,tuples都屬于不可變,而list,dict都屬于可變類型。看下面這段小程序,

點擊(此處)折疊或打開

def func(var1):

var1 = 10

var2 = 200

func(var2)

print var2

func的傳入參數是整數,值為200,在func內部,它試圖把傳入參數賦值為10,結果打印出來的值仍然是200,原因是func的參數是不可變類型。

再看下面這段程序,

點擊(此處)折疊或打開

def func(var1):

var1[0] = 100

var2 = [3,4,5,6,7]

func(var2)

print var2[0]

func的傳入參數是list,屬于可變類型,而函數試圖把這個list的第一個元素用100進行賦值,結果是var2的第一元素從3變為了100,最終打印出來的結果是100。

在實際工作中,如何保證參數在傳遞過程中不發生改變呢?一個辦法是傳遞參數的一份拷貝,比如需要傳一個列表L = [1,2,3]給函數func,那你可以寫成func(L[:])。另一個辦法是使用函數tuple,把list轉換為tuple,像這樣func(tuple(L))。

總結

以上是生活随笔為你收集整理的python函数参数传递机制_Python 学习笔记(一) 理解Python的函数传参机制的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。