Python: 'global' 和 globals().update(var) 之间的区别

标签 python variables global

将变量初始化为 global var 或调用 globals().update(var) 有什么区别。

谢谢

最佳答案

当你说

global var

您是在告诉 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()

如果没有 global 语句,"def f" block 中的 var 将是一个局部变量, 并且设置它的值对“def f” block 之外的 var 没有影响。

var=0
def f():
    var=1
f()
print(var)
# 0  <---- the var outside the "def f" block is unaffected

当您说 globals.update(var) 时,我猜您实际上是指 globals().update(var)。 让我们把它拆开。

globals() 返回一个字典对象。字典的键是对象的名称,而 字典的值是关联对象的值。

每个字典都有一个名为“更新”的方法。所以 globals().update() 是对这个方法的调用。 update 方法需要至少一个参数,并且该参数应该是一个字典。如果你告诉 Python

globals().update(var)

那么 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

关于Python: 'global' 和 globals().update(var) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1589968/

相关文章:

python - 使用Python将OpenCV cv.Rectangle(img,pt1,pt2)转换为NumPy数组

Java 系统属性和环境变量

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

python - 使用循环为列表中的变量赋值

login - Google 全局登录如何运作?

ios - 制作通用变量的最佳方法

python - 使用 Python 从 .txt 文件中获取前 1000 个或定义数量的单词的最简单方法是什么?

Python/Numpy - 计算相等数组元素的总和

python - 从 Python 列表中删除索引列表

c# - 全局变量与 ASP.NET session 状态