电商建站系统,下载个网上销售网站,软件开发工具最重要的信息出口是,分销网站建设方案对于刚接触Python不久的新手#xff0c;Python的函数传参机制往往会让人迷惑。学过C的同学都知道函数参数可以传值或者传地址。比如下面这段代码点击(此处)折叠或打开void func(int input) {input 100;}int a 0;func(a);printf(%d, a);结果应该是打印0#xff…对于刚接触Python不久的新手Python的函数传参机制往往会让人迷惑。学过C的同学都知道函数参数可以传值或者传地址。比如下面这段代码点击(此处)折叠或打开void func(int input) {input 100;}int a 0;func(a);printf(%d, a);结果应该是打印0a的值自始至终都没有改变因为传递给函数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 parametersoption, but it turns out to be very similar to the argument-passing model of the Clanguage (and others) in practice:Immutable arguments are effectively passed “by value.”Objects such as integersand strings are passed by object reference instead of by copying, but becauseyou can’t change immutable objects in place anyhow, the effect is much like makinga copy.Mutable arguments are effectively passed “by pointer.”Objects such as listsand dictionaries are also passed by object reference, which is similar to the way Cpasses 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 simplerstill—it involves just the assignment of objects to names, and it works the same whetherthe objects are mutable or not.也就是说在Python中不可变参数(Immutable arguments)都是可理解为传值的而可变参数(Mutable arguments)都是可以理解为传地址的。而哪些类型是不可变参数呢根据Mark的描述numbersstringstuples都属于不可变而listdict都属于可变类型。看下面这段小程序点击(此处)折叠或打开def func(var1):var1 10var2 200func(var2)print var2func的传入参数是整数值为200在func内部它试图把传入参数赋值为10结果打印出来的值仍然是200原因是func的参数是不可变类型。再看下面这段程序点击(此处)折叠或打开def func(var1):var1[0] 100var2 [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))。