关于python函数的参数问题(对同一块儿地址的操作)

下面有两份代码一份是python,一份是c++,这里python中的变量连续当作参数传递给函数,而导致结果的变化,实际原因是:list是一个变量指向[],每当调用一次函数也就相当于当前list与test是指向同一对象的变量,每次list向末尾添加一个单词后那么,test所指向的对象的值肯定也变化,跟下面c++这个全局变量目前感觉有点相似。

def add(list = []):
    list.append('end')
    return list
test = ['a', 'v', 'd']
print(add(test))        #output ['a', 'v', 'd', 'end']
print(add(test))        #output ['a', 'v', 'd', 'end', 'end']
print(add())            #output ['end']
print(add())            #output ['end', 'end']
#include <iostream>

using namespace std;

string s = "abc";

string change()
{
    return s += 'a';
}
int main()
{

    cout << change() << endl;

    cout << change() << endl;

    return 0;
}

python中传递的list型变量与参数实际操作的是同一块儿地址。也就是当前list指向的对象[]是可变的,函数中对list进行改变,那么test也相应改变,则见代码:

def add(list = None):
    if list is None:
        list = []
    list.append('end')
    return list
test = ['a', 'v', 'd']
print(add(test))            #output ['a', 'v', 'd', 'end']
print(test)            #output ['a', 'v', 'd', 'end']

对于str这种不可变类型来说,函数中对其的改变不能引起原来变量的变化,因为a和s指向的是两个地址

def add(a):
    a += 'a'
    return a

s = 'abc'
print(add(s))       #output abca
print(s)            #output abc

再看看这个,None是个不变对象,因此这里的两个输出相同

def add(list = None):
    if list is None:
        list = []
    list.append('end')
    return list
print(add())        #output ['end']
print(add())        #output ['end']

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/80314416