Python:'global' 和 globals().update(var) 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1589968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Difference between 'global' & globals().update(var)
提问by frank
What is the difference between initializing a variable as global var
or calling globals().update(var)
.
将变量初始化为global var
或调用globals().update(var)
.
Thanks
谢谢
回答by unutbu
When you say
当你说
global var
you are telling Python that var is the same var that was defined in a global context. You would use it in the following way:
你告诉 Python var 是在全局上下文中定义的同一个 var。您可以通过以下方式使用它:
var=0
def f():
global var
var=1
f()
print(var)
# 1 <---- the var outside the "def f" block is affected by calling f()
Without the global statement, the var inside the "def f" block would be a local variable, and setting its value would have no effect on the var outside the "def f" block.
如果没有 global 语句,“def f”块内的 var 将是一个局部变量,设置其值对“def f”块外的 var 没有影响。
var=0
def f():
var=1
f()
print(var)
# 0 <---- the var outside the "def f" block is unaffected
When you say globals.update(var) I am guessing you actually mean globals().update(var). Let's break it apart.
当您说 globals.update(var) 时,我猜您实际上是指 globals().update(var)。让我们把它分开。
globals() returns a dict object. The dict's keys are the names of objects, and the dict's values are the associated object's values.
globals() 返回一个 dict 对象。字典的键是对象的名称,字典的值是关联对象的值。
Every dict has a method called "update". So globals().update() is a call to this method. The update method expects at least one argument, and that argument is expected to be a dict. If you tell Python
每个字典都有一个称为“更新”的方法。所以 globals().update() 是对这个方法的调用。update 方法需要至少一个参数,并且该参数应该是一个 dict。如果你告诉 Python
globals().update(var)
then var had better be a dict, and you are telling Python to update the globals() dict with the contents of the var dict.
那么 var 最好是一个 dict,并且你告诉 Python 用 var dict 的内容更新 globals() dict。
For example:
例如:
#!/usr/bin/env python
# Here is the original globals() dict
print(globals())
# {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}
var={'x':'Howdy'}
globals().update(var)
# Now the globals() dict contains both var and 'x'
print(globals())
# {'var': {'x': 'Howdy'}, 'x': 'Howdy', '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}
# Lo and behold, you've defined x without saying x='Howdy' !
print(x)
Howdy