相关疑难解决方法(0)

作为函数的输入传递的python字典在该函数中表现为全局而不是本地

我对以下行为感到非常困惑.案例1,3和4按我的预期执行,但案例2没有.为什么案例2允许函数全局更改字典条目的值,即使该函数从未返回字典?我使用函数的一个主要原因是将函数中的所有内容与其余代码隔离开来,但如果我选择在函数内部使用相同的变量名称,这似乎是不可能的.我理解在函数中明确定义的任何东西都是该函数的本地函数,但如果字典被定义并作为函数的输入传递,则情况似乎并非如此.

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Run Code Online (Sandbox Code Playgroud)

=============案例1 ===============

>>> def testfun1(a):
...     a=2
... 
>>> a=0
>>> testfun1(a)
>>> a
0
Run Code Online (Sandbox Code Playgroud)

=============案例2 ===============

>>> def testfun2(b):
...     b['test']=2
... 
>>> b={}
>>> testfun2(b)
>>> b
{'test': 2}
Run Code Online (Sandbox Code Playgroud)

=============案例3 ===============

>>> def testfun3():
...     c=2
... 
>>> c=0
>>> testfun3()
>>> c
0
Run Code Online (Sandbox Code Playgroud)

=============案例4 ===============(由这个问题解释:全局词典不需要关键字全局来修改它们吗?)

>>> def testfun4():
...     d['test']=10
... 
>>> …
Run Code Online (Sandbox Code Playgroud)

python variables dictionary global local

38
推荐指数
3
解决办法
5万
查看次数

标签 统计

dictionary ×1

global ×1

local ×1

python ×1

variables ×1