Python: Difference between 'global' & globals().update(var)

寵の児 提交于 2020-01-12 03:20:48

问题


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

Thanks


回答1:


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:

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.

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() returns a dict object. The dict's keys are the names of objects, and the dict's values are the associated object's values.

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)

then var had better be a dict, and you are telling Python to update the globals() dict with the contents of the var 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


来源:https://stackoverflow.com/questions/1589968/python-difference-between-global-globals-updatevar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!