Python:“全局"和"globals().update(var) [英] Python: Difference between 'global' & globals().update(var)

查看:553
本文介绍了Python:“全局"和"globals().update(var)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference between initializing a variable as global var or calling globals().update(var).

谢谢

推荐答案

当你说

global var

您正在告诉Python var是在全局上下文中定义的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:

var=0
def f():
    global var
    var=1
f()
print(var)
# 1  <---- the var outside the "def f" block is affected by calling f()

没有全局语句,"def f"块内的var将是局部变量, 并设置其值对"def f"块外部的var无效.

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.

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). 让我们分开吧.

When you say globals.update(var) I am guessing you actually mean globals().update(var). Let's break it apart.

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

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().update()是对此方法的调用. update方法需要至少一个参数,并且该参数应为字典.如果你告诉Python

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(var)

那么var最好是一个dict,而您是在告诉Python用var dict的内容来更新globals()dict.

then var had better be a dict, and you are telling Python to update the globals() dict with the contents of the var 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:“全局"和"globals().update(var)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆