0
def foo():
    testdict = {'A': '1235', 'B': '6458', 'C': 54156}
    dofoo(testdict)

def dofoo(testdict):
    testdict['A'] = testdict['A'].replace('2', '')

testdict设置时对变量值的引用发生了什么testdict['A']?只有那个项目失去了对原始价值的引用吗?

编辑:

因为如果我会这样做:

def foo():
    testdict = {'A': '1235', 'B': '6458', 'C': 54156}
    dofoo(testdict)

def dofoo(testdict)
    testdict = {'F' : '156', 'G' : '6875'}

然后参考将丢失。那么,如果您设置此类集合的项目,为什么不呢?

4

2 回答 2

2
testdict = {'A': '1235', 'B': '6458', 'C': 54156}

def foo(x):
    x['A'] = 0;

foo(testdict)

print testdict['A']

testdict['A'] 的输出为 0。

这是因为 dict 作为引用传递给 foo 函数。

因此,当您将 testdict 传递给 foo 时,x 不是作为 testdict 副本的新 dict - 它实际上是指向同一个 testdict 的指针。当 x['A'] 改变时,这意味着 testdict['A'] 也会改变。

于 2013-03-16T23:52:30.470 回答
2

在任何给定时间,了解您使用给定名称所指的值非常重要。这就是我的意思:

def doFoo1(testdict):
    testdict["A"] = "test1" # this changes a value contained in testdict
    print(id(testdict)) # the id

def doFoo2(testdict):
    testdict = {some:"new dict"} # this creates a new dict object
    print(id(testdict)) # prints a different id, since testdict is a new object

def foo():
    mydict = {'A': '1235', 'B': '6458', 'C': 54156}
    print(id(mydict))
    doFoo1(mydict)
    print(id(mydict))
    doFoo2(mydict)
    print(id(mydict))

这是我系统上的输出(Windows 7 上的 64 位 Python 3.3):

>>> foo()
59383560
59383560
59383560
59413832
59383560

打印了五个id值,三个(第一个、第三个和第五个)foo来自每个doFoo函数(第二个和第四个)。doFoo2 中的一个是唯一与其他不同的,因为该语句testdict = {some:"new dict"}创建了一个新对象,该对象绑定到该testdict函数命名空间内的名称。该更改不会反映在foo函数中,因为它的mydict名称仍绑定到原始对象。

这是 Python 的一部分,与大多数其他编程语言不同。与 C 中变量名对应于内存中的特定位置的 C 不同,在 Python 中,名称指的是特定对象。如果再次分配给该名称,那只会将该名称重新绑定到另一个对象(根本不会影响原始对象,尽管如果没有其他对它的引用,它可能会被垃圾收集)。

这段代码的一部分(如 Pythonista演示文稿)对于理解这种区别非常有帮助。我认为它的“nametag”隐喻非常有助于理解名称绑定在 Python 中的工作原理。

于 2013-03-17T00:46:06.293 回答