fra*_*ank 9 python variables global
初始化变量global var或调用之间的区别是什么globals().update(var).
谢谢
unu*_*tbu 18
当你说
global var
Run Code Online (Sandbox Code Playgroud)
你告诉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()
Run Code Online (Sandbox Code Playgroud)
如果没有全局语句,"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
Run Code Online (Sandbox Code Playgroud)
当你说globals.update(var)我猜你实际上是指globals().update(var).让我们分开吧.
globals()返回一个dict对象.dict的键是对象的名称,dict的值是关联对象的值.
每个dict都有一个名为"update"的方法.所以globals().update()是对这个方法的调用.update方法至少需要一个参数,并且该参数应该是一个dict.如果你告诉Python
globals().update(var)
Run Code Online (Sandbox Code Playgroud)
var最好是一个dict,你告诉Python使用var dict的内容更新globals()dict.
例如:
#!/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
Run Code Online (Sandbox Code Playgroud)