[英]Why is the global keyword not required in this case?
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
output 产量
bar
Why does this work and why doesn't it require use of the global
keyword? 为什么这样做以及为什么不需要使用global
关键字?
Because you are not assigning to cache
, you are changing the dictionary itself instead. 因为您没有分配 cache
,所以您正在更改字典本身。 cache
is still pointing to the dictionary, thus is itself unchanged. cache
仍然指向字典,因此本身没有变化。 The line cache['foo'] = 'bar'
translates to cache.__setitem__('foo', 'bar')
. 行cache['foo'] = 'bar'
转换为cache.__setitem__('foo', 'bar')
。 In other words, the value of cache
is a python dict
, and that value is itself mutable. 换句话说, cache
的值是python dict
,并且该值本身是可变的。
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. 如果您尝试使用cache = 'bar'
来更改cache
引用的内容,您将更改cache
点,然后您需要global
关键字。
Perhaps this older answer of mine to a similar question helps you understand the difference: Python list doesn't reflect variable change . 也许我对类似问题的这个较老的答案可以帮助您理解差异: Python列表不反映变量 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.