Python: Различие между 'глобальным' и globals () .update (var)

У нас была подобная дилемма. В нашей компании мы решили, инвестируют много времени на платформе, с возможной надеждой на выпуск его сообществу разработчиков ПО с открытым исходным кодом. Бизнес создается с помощью инструментов с открытым исходным кодом (апач, php, и т.д.), пришло время отдать. Мы выбрали двойную лицензию LGPL/MPL. Тем путем мы могли соединиться, фиксирует/улучшения от сообщества, при тихой защите приложений (особенно наш) выполнение сверху его от того, чтобы быть вынужденным пойти открытый исходный код также.

9
задан frank 19 October 2009 в 17:40
поделиться

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. Метод обновления ожидает по крайней мере один аргумент, и этот аргумент должен быть dict. Если вы сообщаете Python

globals().update(var)

, тогда var лучше использовать dict, и вы говорите Python, чтобы он обновил globals () dict содержимым 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
18
ответ дан 4 December 2019 в 11:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: