为什么在这种情况下不需要全局关键字? [英] Why is the global keyword not required in this case?
问题描述
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
输出
output
bar
为什么这个工作以及为什么它不需要使用 global
关键字
Why does this work and why doesn't it require use of the global
keyword?
推荐答案
因为您不是赋值到 cache
,您改变字典本身。 cache
仍然指向字典,因此本身不变。 cache ['foo'] ='bar'
行转换为 cache .__ setitem __('foo','bar')
。换句话说, cache
的值是一个python dict
,并且该值本身是可变的。
Because you are not assigning to cache
, you are changing the dictionary itself instead. cache
is still pointing to the dictionary, thus is itself unchanged. The line cache['foo'] = 'bar'
translates to cache.__setitem__('foo', 'bar')
. In other words, the value of cache
is a python dict
, and that value is itself mutable.
如果您试图通过使用 cache ='bar'$ c来更改
cache 点数,然后你需要
全局
关键字。
If you tried to change what cache
refers to by using cache = 'bar'
instead, you would be changing what cache
points to and then you need the global
keyword.
也许这个类似问题的这个较老的答案可以帮助你理解不同之处: Python列表不反映变量变化。
Perhaps this older answer of mine to a similar question helps you understand the difference: Python list doesn't reflect variable change.
这篇关于为什么在这种情况下不需要全局关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!