有条件地修改全局变量

时间:2012-08-23 14:25:24

标签: python

我想做这样的事情,但是我得到了一个SyntaxWarning并且没有按预期工作

RAWR = "hi"
def test(bool):
    if bool:
        RAWR = "hello"   # make RAWR a new variable, don't reference global in this function
    else:
        global RAWR
        RAWR = "rawr"    # reference global variable in this function
    print RAWR           # if bool, use local, else use global (and modify global)

我如何让它工作?传入True或False会修改全局变量。

2 个答案:

答案 0 :(得分:5)

你做不到。在范围内,特定名称指的是局部变量,或指非局部(例如全局或外部函数)变量。不是都。 global RAWR行使RAWR成为整个范围的全局(这就是为什么你得到警告,它没有做你认为它做的事情),就像赋值给变量使它成为本地的整个范围。编辑:感谢veredesmarald,我们现在知道它实际上是Python 2中的语法错误。这一半答案仅适用于Python 3。

您应该只使用不同名称的局部变量,并在要将其“提升”为全局的分支中,将全局设置为局部变量。 (或者根本不使用全局变量。)

答案 1 :(得分:1)

唯一容易的方法就是

RAWR = "hi"
def test(newone):
    if newone:
        lR = "hello"   # make RAWR a new variable, don't reference global in this function
    else:
        global RAWR
        lR = RAWR      # reference global variable in this function
    print lR           # if bool, use local, else use global (and modify global)
    # modify lR and then
    if not newone:
        RAWR = lR

然而,另一种方法可能是将类和对象的概念滥用到您的目的。

class store_RAWR(object):
    RAWR = "hi"
    def __init__(self, new): self.RAWR = new

def test(newone):
    if newone:
        myR = store_RAWR("hello") # get a (temporary) object with a different string
    else:
        myR = store_RAWR # set the class, which is global.
    # now modify myR.RAWR as you need

但这需要更改使用全局名称的其他程序部分。

相关问题