gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:37:06 28 4
gpt4 key购买 nike

将变量初始化为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com