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

Python中函数内字典直接赋值未同步全局的原因

为什么函数内修改dict1不影响全局变量,而用update修改dict2却能改变全局?

先看你的测试代码:

dict1 = {}
dict2 = {"sui": "haiyaa"}
def bruh(dictionary1, dictionary2):
    dictionary1 = {"sup":"mgoi", "bruh":"moment"}
    dictionary2.update({"sup":"mgoi", "bruh":"moment"})
    print(dictionary1)
    print(dictionary2)
    
bruh(dict1, dict2)
print(dict1)
print(dict2)

输出结果:

{'sup': 'mgoi', 'bruh': 'moment'}
{'sui': 'haiyaa', 'sup': 'mgoi', 'bruh': 'moment'}
{}
{'sui': 'haiyaa', 'sup': 'mgoi', 'bruh': 'moment'}

核心原因:Python的参数传递是「传对象引用」,可变对象的修改分两种情况

  • dict1未变化的原因:
    调用bruh(dict1, dict2)时,局部变量dictionary1拿到的是全局dict1的对象引用。但函数里执行dictionary1 = {"sup":"mgoi", "bruh":"moment"}时,是给dictionary1重新赋值了一个全新的字典对象——此时局部变量的引用指向了新对象,和原来的全局dict1彻底断开关联,所以全局dict1还是原来的空字典。

  • dict2被修改的原因:
    局部变量dictionary2拿到的是全局dict2的对象引用,执行dictionary2.update(...)时,是直接调用字典对象的内置方法,修改的是对象本身的内容。因为dictionary2和全局dict2指向的是同一个字典对象,所以全局dict2的内容会同步变化。

验证:如何让全局dict1也被修改?

把函数里给dictionary1重新赋值的代码改成调用update方法:

def bruh(dictionary1, dictionary2):
    dictionary1.update({"sup":"mgoi", "bruh":"moment"})  # 替换成update操作
    dictionary2.update({"sup":"mgoi", "bruh":"moment"})
    print(dictionary1)
    print(dictionary2)

此时全局dict1会变成{'sup': 'mgoi', 'bruh': 'moment'},因为你直接修改了它指向的对象内容,而非重新赋值新对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:50:23