从if语句嵌套在for循环中使变量成为全局变量

时间:2018-07-06 19:00:57

标签: python variables scope global-variables

我有一个典型的新手问题,即将函数的结果放入全局范围,我通常可以在简单的示例中了解局部变量和全局变量的工作方式,但是我很难理解如果嵌套了if语句时会发生什么情况for循环。

下面是我正在使用的原始代码。我正在尝试将thisItem的结果应用于全局范围。

def getTheFirstPoint(selection):
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'LOCAL', thisItem
            return thisItem
    return None

我一直在尝试这样的事情:

thisItem = ''

def getTheFirstPoint(selection):
    global thisItem
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'LOCAL', thisItem
            #return thisItem
    #return None

getTheFirstPoint(thisItem)
print 'GLOBAL:', thisItem

我有时看到不需要在函数外部显式设置全局变量-我需要“ thisItem =''”吗?

是否需要退货?

要全局访问此项目需要做什么?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果您运行代码:

thiItem = ''

在内部函数定义中,将创建新的局部变量。如果您确实在函数中运行以下代码

global thisItem
thisItem = ''

将修改全局变量。运行for循环时,将创建新的局部变量for [newVarName] in [iterable]。将thisItem定义为全局后,请勿在 for 循环中再次使用此名称。

如果您希望根据条件修改全局变量,则下面的代码将起作用:

thisItem = ''

def getTheFirstPoint(selection):
    global thisItem
    for item in selection:
        if type(item) == GSNode:
            print 'LOCAL', item
            # Modify global variable.
            thisItem = item
            #return thisItem
    #return None

getTheFirstPoint(thisItem)
print 'GLOBAL:', thisItem

建议。我觉得Python Generators可能已被您全用,还请考虑更紧密地了解有关global vs local variables的信息。

答案 1 :(得分:0)

我曾经看到过有时不需要在函数外部显式设置全局变量-我需要“ thisItem =''“吗? 如果在函数内部创建变量thisItem,则将在该函数中创建局部变量。如果您使用

previous_function():
    thisItem = ''
new_function():
    global thisItem 
    thisItem = 'updated value'

然后,当您在new_function中调用该值时,该值将被覆盖。这就是为什么您需要在其他函数之外定义它的原因。

是否需要退货? 不,不需要退货。您可以从任何其他函数调用全局变量。如果您有另一个具有相同名称的变量,则需要指定要使用全局定义而不是本地定义,如上例所示。

要全局访问此项目需要做什么? 您可以按如下方式使用它:

thisItem = ''
def getTheFirstPoint(selection):
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'GLOBAL', thisItem
def some_new_function():
    global thisItem
    thisItem = 'modified value'