python 参数是通过引用传递的?

python parameters are passed by reference?

网上很多文章都说python参数是按引用传递的。但是从这个片段来看,调用函数 test() 后变量 d 没有改变。它不同于 C/C++。有人可以解释一下吗?谢谢

def test(_d : dict):
    _d = dict()
    _d.update({'D': 4})
    print("Inside the function",_d)
    return

d = {'A': 1,'B':2,'C':3}
test(d)
print("outside the function:", d) # expected: {'D:4}

这里没什么复杂的。

当你有 _d = dict() 时,你刚刚为 new 字典创建了一个新名称 _d(函数 test 的局部)和丢失了引用全局字典 d 的本地名称 _d 最初作为 _d 传递给该函数:

def test(_d : dict):
    print("Passed _d id:",id(_d))
    _d = dict()
    print("new _d id:",id(_d))
    _d.update({'D': 4})
    print("Inside the function",_d)
    return

d = {'A': 1,'B':2,'C':3}
print('Passed d id:',id(d))
test(d)
print("outside the function:", d) # expected: {'A':1, 'B':2, 'C':3, 'D:4}

打印:

Passed d id: 4404101632
Passed _d id: 4404101632
new _d id: 4405135680
Inside the function {'D': 4}
outside the function: {'A': 1, 'B': 2, 'C': 3}

现在试试:

def test(_d : dict):
    print("Passed _d id:",id(_d))
    # _d = dict()
    print("new _d id?:",id(_d))
    _d.update({'D': 4})
    print("Inside the function",_d)
    return

d = {'A': 1,'B':2,'C':3}
print('Passed d id:',id(d))
test(d)
print("outside the function:", d) # expected: {'A':1, 'B':2, 'C':3, 'D:4}

打印:

Passed d id: 4320473600
Passed _d id: 4320473600
new _d id?: 4320473600
Inside the function {'A': 1, 'B': 2, 'C': 3, 'D': 4}
outside the function: {'A': 1, 'B': 2, 'C': 3, 'D': 4}

请注意,在第二种情况下,id 在所有三个打印位置都是相同的,因此它是 相同的对象;在第一种情况下,id 发生变化,因此在 _d = dict() 被调用后您有一个 不同的对象


注:

由于 d 是全局的和可变的,这也按预期工作:

def test():
    d.update({'D': 4})

d = {'A': 1,'B':2,'C':3}
test()
print(d) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}