Bun*_*bit 16 python global-variables
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
Run Code Online (Sandbox Code Playgroud)
产量
bar
Run Code Online (Sandbox Code Playgroud)
为什么这样做以及为什么不需要使用global关键字?
Mar*_*ers 15
因为你没有分配到cache,要更改字典本身,而不是.cache仍然指向字典,因此本身没有变化.该行cache['foo'] = 'bar'转换为cache.__setitem__('foo', 'bar').换句话说,值cache是python dict,并且该值本身是可变的.
如果您尝试cache使用cache = 'bar'相反的方式更改引用的内容,则会更改cache指向的内容,然后您需要global关键字.
也许我对类似问题的这个较老的答案可以帮助您理解差异:Python列表不反映变量.
| 归档时间: |
|
| 查看次数: |
2310 次 |
| 最近记录: |