You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典作为函数参数传递:为何fun2无法修改原字典?

Python字典作为函数参数的修改差异问题解析

原本以为Python中字典作为函数参数传递类似C++的传引用,函数应该能修改传入的字典,但三次实验结果不一致。问题是:为什么fun2无法修改x的值,而fun1和fun3可以做到?Python版本为3.10.12。

Python测试代码

def fun1(x):
    x["c"] = "c"

def fun2(x):
    x = {"ds": "ds"}

def fun3(x):
    c = {"ds": "ds"}
    x["c"] = c

def main():
    d1 = {"a": "a", "b": "b", "c": {}}
    d2 = {"a": "a", "b": "b", "c": {}}
    d3 = {"a": "a", "b": "b", "c": {}}

    fun1(d1)
    fun2(d2["c"])
    fun3(d3)

    print(d1)
    print(d2)
    print(d3)

if __name__ == "__main__":
    main()

Python输出结果

{'a': 'a', 'b': 'b', 'c': 'c'}
{'a': 'a', 'b': 'b', 'c': {}}
{'a': 'a', 'b': 'b', 'c': {'ds': 'ds'}}

更新:问题关键结论

Python参数传递是传值,类似C++中的fun和fun1

C++对比示例代码

#include <iostream>

void fun(int *x){
    // 直接操作指针指向的内容,会影响原指针指向的值
    *x = 10;
}

void fun1(int *x){
    // 指针按值传递,函数内的x是原指针的副本
    // 修改x本身不会影响原指针,但修改*x会影响原内容
    x = new int(20);
    std::cout << "This is function1. " << *x << std::endl;
}

void fun2(int *&x){
    // 指针按引用传递,函数内的x是原指针的引用
    // 修改x本身会直接改变原指针
    x = new int(30);
    std::cout << "This is function2. " << *x << std::endl;
}

int main(){
    int *a = new int(1);
    fun(a);
    std::cout << *a << std::endl;
    fun1(a);
    std::cout << *a << std::endl;
    fun2(a);
    std::cout << *a << std::endl;

    return 0;
}

C++输出结果

10
This is function1. 20
10
This is function2. 30
30

核心原因解析

Python的参数传递本质是传对象引用的值,和C++中传递指针的值逻辑一致:

  • fun1和fun3中,函数参数x是原字典对象的引用副本,通过x["c"] = ...操作的是引用指向的字典内部元素,直接修改了原对象的内容,就像C++中fun函数修改*x会改变原指针指向的值。
  • fun2中,x = {"ds": "ds"}是给参数x重新绑定了一个新的字典对象,这相当于C++fun1里x = new int(20)——修改的是参数本身(引用副本/指针副本),而非原对象的内容,因此原字典不会被改变。

内容的提问来源于stack exchange,提问作者a171232886

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:14:50